<?php

namespace app\api\logic;

use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use app\data\util\HttpUtil;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Cache;

use app\order\logic\OrderSourceLogic;
use app\api\logic\CheckLogic;

class ApiOrderLogic extends BasicLogic
{
    public function __construct()
    {

    }

    public function PollingStores()
    {
        $where2[] = ['type', '=', "shopify"];
        $shop_id = 0;
        $shops = Cache::store('redis')->get('shops_shopify');
        if (empty($shops)) {  
            $shopRecords = Db::name('shops')
                ->where($where2)
                ->where('status',1)
                ->field("id")->select()->toarray();
            if(!empty($shopRecords)){
                $shops = array_column($shopRecords, 'id');
                Cache::store('redis')->set('shops_shopify', $shops, 3600 * 24); // 缓存24小时  
            }
        } 
        if (!empty($shops)) {  
            $shop_id = array_shift($shops); 
            if (!empty($shops)) {  
                Cache::store('redis')->set('shops_shopify', $shops, 3600 * 24);
            }else{
                Cache::store('redis')->delete('shops_shopify');
            }
        }
        return $shop_id;
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 订单详情
     * @author zhangheng
     */
    public function ApiOrderInfo($params = [])
    {
        $order_id        = $params['order_id'] ?? 0;
        $shop_id        = $params['shop_id'] ?? 0;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();

        if($shop_id == 20){
            $version        = Config('Logisticskey.shopline.api_versoin');
            $url            = $shop_info['myshopify_domain'].$version . "/orders/".$order_id.".json";
            $return = HttpUtil::getUrlshopline($url, $shop_info);
            halt($return);
        }else{
            $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id.".json";
            $orders = HttpUtil::getUrl($url, $shop_info);
            $order = $orders['order'] ?? [];
            if (!empty($order)) {
                date_default_timezone_set('Asia/Shanghai');
                // $this->SynchronizzeModifications($order,$shop_id);
            }
            halt($orders);
        }
        
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 订单列表
     * @author zhangheng
     */
    public function ApiOrderList($params = [])
    {
        $type           = $params['type'] ?? '2'; //1更新 2获取历史记录
        $shop_id        = $params['shop_id'] ?? 0;
        
        if(empty($shop_id)){
            //轮询店铺
            $shop_id = $this->PollingStores();
            if (empty($shop_id)) {
                return  $this->jsonMessage(201,false,'暂无店铺',null);
            }
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.orders_path');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        
        switch ($type) {
            case '1':
                $limit = 50;
                
                $last_order = Db::name('order')
                    ->where('shop_id', $shop_info['id'])
                    ->order(['created_at' => 'desc'])
                    ->find();
                if (!empty($last_order['created_at'])) {
                    $created_at_min = $last_order['created_at'];
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $created_at_min1 = date('Y-m-1', time());
                    $created_at_min2 = date('H:i:s', time());
                    $created_at_min = $created_at_min1 . 'T' . $created_at_min2 . '-04:00';
                }
                $url = $url . '?created_at_min=' . $created_at_min . '&limit=' . $limit . '&status=any';
                
                break;
            case '2':
                $limit = 50;
                    if (!empty($shop_info['ControlUpdateTime'])) {
                        $created_at_max = $shop_info['ControlUpdateTime'];
                    } else {
                        date_default_timezone_set('Asia/Shanghai');
                        $created_at_max1 = date('Y-m-d', time());
                        $created_at_max2 = date('H:i:s', time());
                        $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
                    }
                $url = $url . '?created_at_max=' . $created_at_max . '&limit=' . $limit . '&status=any';
                break;
            default:
        }
        $return = HttpUtil::getUrl($url, $shop_info);

        if (!empty($return['errors'])) {
            return  $this->jsonMessage(201,false,json_encode($return['errors']),null);
        }
        if(!empty($return)){
            Db::startTrans();
            try {
                //存入数据
                $this->ProcessOrders($return,$shop_info['id'],$type);
                
                Db::commit();
                return json(DefaultResponse(200, true, '操作成功', ''));
            } catch (ValidateException $e) {
                Db::rollback();
                return json(DefaultResponse(200, true, $e->getError(), ''));
            } catch (\Exception $e) {
                Db::rollback();
                return json(DefaultResponse(200, true, $e->getMessage(), ''));
            }
        }else{
            return  $this->jsonMessage(201,false,'暂无数据',null);
        }
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 订单列表--临时更新
     * @author zhangheng
     */
    public function ApiOrderListTemporary($params = [])
    {
        $order_append = Db::name('order_append')
            ->where('TemporaryUpdateTime',0)
            ->find();

        $order = [];
        if(!empty($order_append['json'])){
            $order = json_decode($order_append['json'],true);
        }
        
        if(!empty($order)){
            
            Db::startTrans();
            try {
                //存入数据
                $this->SynchronizzeModifications($order,$order_append['shop_id']);
                
                //更新一次
                $update = [];
                $update['TemporaryUpdateTime'] = time();
                $order_append = Db::name('order_append')
                    ->where('id',$order_append['id'])
                    ->update($update);
                
                Db::commit();
                return json(DefaultResponse(200, true, '操作成功', ''));
            } catch (ValidateException $e) {
                Db::rollback();
                return json(DefaultResponse(200, true, $e->getError(), ''));
            } catch (\Exception $e) {
                Db::rollback();
                return json(DefaultResponse(200, true, $e->getMessage(), ''));
            }
        }else{
            return json(DefaultResponse(200, true, '暂无数据', ''));
        }
    }

    /**
    * 方法详情
    * @param array params
    */
    public function ProcessOrders($return,$shop_id,$type)
    {
        $ControlUpdateTime = 0;
        
        $orders = $return['orders'];
        if (is_array($orders) && !empty($orders)) {
            date_default_timezone_set('Asia/Shanghai');
            foreach ($orders as  $order) {
            $row = Db::name('order')->where('order_id',$order['id'])->find();
                if(!empty($row)){
                //     //2.同步修改
                    // if($type !== '2'){
                        $this->SynchronizzeModifications($order,$shop_id);
                    // }
                }else{
                    //1.新增时创建
                    $this->SynchronizeModifications($order,$shop_id);
                }
                if($type == 2){
                    //移除时间字符串中的'T'和时区部分
                    if(!empty($ControlUpdateTime)){
                        if($shop_id == 20){
                            $createtime = $this->dateTimeStr($order['created_at']);
                            $ControlUpdateTimeTimeStamp = $this->dateTimeStr($ControlUpdateTime);
                            if($ControlUpdateTimeTimeStamp <= $createtime){
                                $ControlUpdateTime = $order['created_at'];
                            }
                        }else{
                            $createtime = $this->dateTimeStr($order['created_at']);
                            $ControlUpdateTimeTimeStamp = $this->dateTimeStr($ControlUpdateTime);
                            if($ControlUpdateTimeTimeStamp > $createtime){
                                $ControlUpdateTime = $order['created_at'];
                            }
                        }
                    }else{
                        $ControlUpdateTime = $order['created_at'];
                    }
                }
            }

            if($type == 2){
                $update_shop['ControlUpdateTime'] = $ControlUpdateTime;
                Db::name('shops')
                    ->where('id', $shop_id)
                    ->update($update_shop);
            }

        }
        return true;
    }
    
    /**
    * 新增订单
    * @param array params
    */
    public function SynchronizeModifications($order,$shop_id)
    {

        //kisslove新店铺
        if($shop_id == 22){
            $createtime = $this->dateTimeStr($order['created_at']);
            //判断时间戳 从美国时间6-7日开始
            if($createtime < 1749139200){
                return true;
            }
        }
        // shopline
        if($shop_id == 20){
            //订单主表
            $type = "insert";
            $this->order_handle_shopline($order,$shop_id,$type);

            //order_info订单详情
            $skuinfo = $this->order_info_handle_shopline($order,$shop_id);

            //order_achievement订单金额
            $type = "insert";
            $this->order_achievement_handle_shopline($order,$shop_id,$skuinfo,$type);

            //order_source客户行为日志
            $this->order_source_handle_shopline($order,$shop_id,$skuinfo);

            //客户收货地址信息表;
            self::get_order_shipping_shopiline($order,$shop_id);

            //订单基础信息表;
            self::get_order_process_shopiline($order,$shop_id);

            //order_customer客户
            $this->order_customer_handle_shopline($order,$shop_id);

            return  true;
        }
        //订单主表
        $type = "insert";
        $this->order_handle($order,$shop_id,$type);

        //order_info订单详情
        $skuinfo = $this->order_info_handle($order,$shop_id);

        //order_achievement订单金额
        $type = "insert";
        $this->order_achievement_handle($order,$shop_id,$skuinfo,$type);

        //order_source客户行为日志
        $this->order_source_handle($order,$shop_id,$skuinfo);

        //order_customer客户
        $this->order_customer_handle($order,$shop_id);

        //客户物流地址信息表;
         self::get_order_shipping($order,$shop_id);

         //订单基础信息表;
         self::get_order_process($order,$shop_id);

        //update 205-04-11 同时数据推送到拆分队列;
        self::add_hwc_queue($order);
        return  true;
    }

    
    /**
    * 新增修改订单
    * @param array params
    */
    public function SynchronizzeModifications($order,$shop_id)
    {
        //kisslove新店铺
        if($shop_id == 22){
            $createtime = $this->dateTimeStr($order['created_at']);
            //判断时间戳 从美国时间6-7日开始
            if($createtime < 1749139200){
                return true;
            }
        }
        // shopline
        if($shop_id == 20){
            //订单主表
            $type = "update";
            $this->order_handle_shopline($order,$shop_id,$type);
            //订单主表

            //order_achievement订单金额
            $type = "update";

            //order_info订单详情
            $skuinfo = $this->order_info_handle_shopline($order,$shop_id);

            $this->order_achievement_handle_shopline($order,$shop_id,$skuinfo,$type);

            //order_fulfillments物流轨迹----成功时调用一次
            $this->order_fulfillments_handle_shopline($order,$shop_id);

            //order_customer客户
            $this->order_customer_handle_shopline($order,$shop_id);

            //refunds退款
            $this->order_refunds_handle_shopline($order,$shop_id);

            //order_source客户行为日志
            $this->order_source_handle_shopline($order,$shop_id,$skuinfo);

            return true;
        }
        //订单主表
        $type = "update";
        $this->order_handle($order,$shop_id,$type);
        //订单主表

        //order_achievement订单金额
        $type = "update";
        //order_info订单详情
        $skuinfo = $this->order_info_handle($order,$shop_id);

        $this->order_achievement_handle($order,$shop_id,$skuinfo,$type);

        //order_fulfillments物流轨迹----成功时调用一次
        $this->order_fulfillments_handle($order,$shop_id);

        //order_customer客户
        $this->order_customer_handle($order,$shop_id);

        //refunds退款
        $this->order_refunds_handle($order,$shop_id);

        //order_source客户行为日志
        $this->order_source_handle($order,$shop_id,$skuinfo);

        return true;
    }


    /**
     * @desc   获取物流信息接口
     * @author luckyXiong
     * @date   2025-03-14
     */
    private function get_order_shipping($order,$shop_id){
            $list = $order['shipping_address']??'';
            if(!$list)  return  true;
            $info = [
                'shop_id'     =>$shop_id,
                'order_id'    =>$order['id']??'',
                'first_name'  =>$list['first_name']??'',
                'last_name'   =>$list['last_name']??'',
                'name'        =>$list['name']??'',
                'phone'       =>$list['phone']??'',
                'country'     =>$list['country']??'',
                'province'    =>$list['province']??'',
                'city'        =>$list['city']??'',
                'zip'         =>$list['zip']??'',
                'country_code'=>$list['country_code']??'',
                'province_code'=>$list['province_code']??'',
                'address1'     =>$list['address1']??'',
                'address2'     =>$list['address2']??'',
                'create_time'  =>date("Y-m-d H:i:s", time()),
            ];
        $exist_info = Db::name('order_shipping')->where(['order_id'=>$order['id']])->find();
        if(!$exist_info){
            Db::name('order_shipping')->insert($info);
        }
        return  true;
    }

    private function get_order_process_shopiline($order,$shop_id){
        $shop_numbers = Config('Logisticskey.shop_number');
        $number   = $shop_numbers[$shop_id]??'7256335';
        $order_name = $order['name']??'';
        $order_number = $number.'-'.$order_name;
        $title = $order['shipping_lines'][0]['title'] ?? "";
        $title = mb_convert_encoding($title, 'ASCII', 'UTF-8');
        $info = [
            'package_id'  =>get_package_id(),
            'order_number'=>$order_number,
            'order_id'    =>$order['id']??'',
            'number'      =>$order['name']??'',
            'shop_id'     =>$shop_id,
            'total_price' =>$order['payment_details'][0]['pay_amount']??'',
            'code_title'  =>$title ?? "",
            'country'     =>$order['shipping_address']['country_code']??'',
            'currency'    =>$order['currency']??'',
            'create_time' =>date("Y-m-d H:i:s", time()),
        ];
        $exist_info = Db::name('order_process')->where(['order_id'=>$order['id']])->find();
        if(!$exist_info){
            Db::name('order_process')->insert($info);
        }
        return  true;
    }


    /**
     * @desc   获取订单信息接口
     * @author luckyXiong
     * @date   2025-03-14
     */
    private function get_order_process($order,$shop_id){
        $shop_numbers = Config('Logisticskey.shop_number');
        $number   = $shop_numbers[$shop_id]??'7256335';
        $order_name = $order['order_number']??'';
        $order_number =  $number.'-'.$order_name;
        $title = $order['shipping_lines'][0]['title'] ?? "";
        $title = mb_convert_encoding($title, 'ASCII', 'UTF-8');
        $info = [
            'package_id'  =>get_package_id(),
            'order_number'=>$order_number,
            'order_id'    =>$order['id']??'',
            'number'      =>$order['order_number']??'',
            'shop_id'     =>$shop_id,
            'total_price' =>$order['current_total_price']??'',
            'code_title'  =>$title ?? "",
            'country'     =>$order['billing_address']['country_code']??'',
            'currency'    =>$order['currency']??'',
            'create_time' =>date("Y-m-d H:i:s", time()),
        ];
        $exist_info = Db::name('order_process')->where(['order_id'=>$order['id']])->find();
        if(!$exist_info){
            Db::name('order_process')->insert($info);
        }
        return  true;
    }


    public function add_hwc_queue($order){
        //update 205-04-11 同时数据推送到拆分队列;
        MqTaskPushLogic::mq_task_push(
            '',
            MqQueueName::QUEUE_ORDER_HWC_QUEUE,
            [
                'order_id' => $order['id'],
            ],
            false
        );
        return  true;
    }





    /**
     * @desc   获取物流信息接口
     * @author luckyXiong
     * @date   2025-03-14
     */
    private function get_order_shipping_shopiline($order,$shop_id){
        $list = $order['shipping_address']??'';
        if(!$list)  return  true;
        $info = [
            'shop_id'     =>$shop_id,
            'order_id'    =>$order['id']??'',
            'first_name'  =>$list['first_name']??'',
            'last_name'   =>$list['last_name']??'',
            'name'        =>$list['name']??'',
            'phone'       =>$list['phone']??'',
            'country'     =>$list['country']??'',
            'province'    =>$list['province']??'',
            'city'        =>$list['city']??'',
            'zip'         =>$list['zip']??'',
            'country_code'=>$list['country_code']??'',
            'province_code'=>$list['province_code']??'',
            'address1'     =>$list['address1']??'',
            'address2'     =>$list['address2']??'',
            'create_time'  =>date("Y-m-d H:i:s", time()),
        ];
        $exist_info = Db::name('order_shipping')->where(['order_id'=>$order['id']])->find();
        if(!$exist_info){
            Db::name('order_shipping')->insert($info);
        }
        return  true;
    }








    /**
    * @desc    订单主表
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_handle($order,$shop_id,$type)
    {
        $title = $order['shipping_lines'][0]['title'] ?? "";
        $title = mb_convert_encoding($title, 'ASCII', 'UTF-8');
        switch ($type) {
            case 'insert':
                $insert = [
                    'order_id' => $order['id'],
                    'shop_id' => $shop_id,
                    'name' => $order['name'],
                    'number' => $order['number'],
                    'order_number' => $order['order_number'],
                    'total_price' => $order['total_price'],
                    'currency' => $order['currency'] ?? "",
                    'financial_status' => $order['financial_status'] ?? "",
                    'fulfillment_status' => $order['fulfillment_status'] ?? "",
                    'tracking_number' => $order['fulfillments'][0]['tracking_number'] ?? "",
                    'created_at' => $order['created_at'],
                    'updated_at' => $order['updated_at'],
                    'closed_at' => $order['closed_at'] ?? "",
                    'createtime' => $this->dateTimeStr($order['created_at']),
                    'updatetime' => $this->dateTimeStr($order['updated_at']),
                    'payment_gateway_names' => $order['payment_gateway_names'][0] ?? "",
                    'country_code' => $order['shipping_address']['country_code'] ?? "",
                     'code_title' => $title ?? "",
                ];
                break;
            case 'update':
                $insert = [
                    'total_price' => $order['total_price'],
                    'financial_status' => $order['financial_status'] ?? "",
                    'fulfillment_status' => $order['fulfillment_status'] ?? "",
                    'tracking_number' => $order['fulfillments'][0]['tracking_number'] ?? "",
                    'created_at' => $order['created_at'],
                    'updated_at' => $order['updated_at'],
                    'closed_at' => $order['closed_at'] ?? "",
                    'createtime' => $this->dateTimeStr($order['created_at']),
                    'updatetime' => $this->dateTimeStr($order['updated_at']),
                     'code_title' => $title ?? "",
                ];
                break;
            default:
        }
        $orderdb = Db::name('order')->where('order_id',$order['id'])->find();
        if(!empty($orderdb)){
            Db::name('order')->where('order_id',$order['id'])->update($insert);
        }else{
            Db::name('order')->insert($insert);
        }
        return true;
    }

    /**
    * @desc    order_info订单详情
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_info_handle($order,$shop_id)
    {
        $skuquantity = 0;
        $arr_source_skus = [];
        $arr_source_spus = [];

        if(isset($order['line_items']) && !empty($order['line_items'])){
            $line_items = $order['line_items'];
            Db::name('order_skuinfo')->where('order_id',$order['id'])->delete();
            foreach ($line_items as $line_item) {
                $arr_info = [];
                //update  2025-04-15 [sku] => SEEL-WFP 去掉
                if($line_item['sku']=='SEEL-WFP'){
                    $arr_info['is_seel'] = 1;
                }
                $arr_info['order_id'] = $order['id'];
                $arr_info['shop_id'] = $shop_id;
                $arr_info['info_id'] = $line_item['id'];
                $arr_info['product_id'] = $line_item['product_id'] ?? "";
                $arr_info['name'] = $line_item['name'] ?? "";
                $arr_info['name'] = $this->removeNonAscii($arr_info['name']);
                $arr_info['variant_id'] = $line_item['variant_id'] ?? "";
                $arr_info['sku'] = $line_item['sku'] ?? "";

                $arr_info['created_at'] = $order['created_at'];
                $arr_info['updated_at'] = $order['updated_at'];

                //订单详情加spu
                $arr_info['spu'] = "";
                $dashPos = strpos($arr_info['sku'], '-');  
                if ($dashPos !== false) {  
                    $arr_info['spu'] = substr($arr_info['sku'], 0, $dashPos);  
                }

                $arr_info['variant_title'] = $line_item['variant_title'] ?? "";
                $arr_info['variant_title'] = $this->removeNonAscii($arr_info['variant_title']);
                $arr_info['quantity'] = $line_item['quantity'] ?? "";
                $arr_info['price'] = $line_item['price'] ?? 0;
                //统计件数
                $skuquantity = $skuquantity + $this->CountTheNumberOfItems($arr_info,$order);
                //skus集合
                if(!empty($arr_info['sku'])){
                    $arr_source_skus[] = $arr_info['sku'];
                }
                if(!empty($arr_info['spu'])){
                    $arr_source_spus[] = $arr_info['spu'];
                }

                $order_info = Db::name('order_info')->where('info_id',$arr_info['info_id'])->find();
                if(!empty($order_info)){
                    Db::name('order_info')->where('info_id',$arr_info['info_id'])->update($arr_info);
                }else{
                    Db::name('order_info')->insert($arr_info);
                }
            }
        }
        $arr_source_skus = array_unique($arr_source_skus);
        if(!empty($arr_source_skus)){
            $arr_source_skus = implode(',',$arr_source_skus);
        }else{
            $arr_source_skus = '';
        }
        $arr_source_spus = array_unique($arr_source_spus);
        if(!empty($arr_source_spus)){
            $arr_source_spus = implode(',',$arr_source_spus);
        }else{
            $arr_source_spus = '';
        }
        
        $skuinfo = [
            'arr_source_skus' => $arr_source_skus,
            'arr_source_spus' => $arr_source_spus,
            'skuquantity' => $skuquantity,
        ];
        return $skuinfo;
    }

    /**
    * @desc    order_info订单详情
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_skuinfo()
    {
        //日期
        $where[]  = ['createtime', '>=', 1725120000];
        $where[]  = ['createtime', '<=', 1735660800];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $count = Db::name('order')
            ->where($where)
            ->count();
            // halt($count);
            
        if($count <= 0) {
            echo "没有数据";
        }
        // halt($count);
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 348370;
        for ($i = 697; $i <= $page; $i++){
            $lists = Db::name('order')
                ->where($where)
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])->toarray();
        
            foreach($lists['data'] as $k=>$v){
                // halt($v);
                $skuquantity = $this->order_skuinfos($v);
                if($skuquantity <= 0) {
                    echo $v['order_id']."没有数据" . PHP_EOL;
                    continue;
                }
                Db::name('order_achievement')->where('order_id',$v['order_id'])->update([
                    'skuquantity' => $skuquantity,
                ]);

                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . "条,已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
        }
    }

    /**
    * @author  zhangheng
    */
    public function order_skuinfos($v)
    {
        $skuquantity = 0;
        $line_items = Db::name('order_info')
            ->field('shop_id,order_id,product_id,variant_id,sku,quantity')
            ->where('order_id',$v['order_id'])
            ->select()->toarray();
        if(empty($line_items)){
            echo "没有详情数据" . PHP_EOL;;
            return false;
        }
        Db::name('order_skuinfo')->where('order_id',$v['order_id'])->delete();
        foreach ($line_items as $arr_info) {
            //统计件数
            $skuquantity = $skuquantity + $this->CountTheNumberOfItems($arr_info,$v);
        }
        return $skuquantity;
    }
    


    /**
    * @desc    order_achievement订单金额
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_achievement_handle($order,$shop_id,$skuinfo,$type)
    {
        switch ($type) {
            case 'insert':
                $arr_achievement['name'] = $order['name'] ?? "";
                $arr_achievement['financial_status'] = $order['financial_status'] ?? "";
                $arr_achievement['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                $arr_achievement['tracking_number'] = $order['fulfillments'][0]['tracking_number'] ?? "";
                $arr_achievement['shipment_status'] = $order['fulfillments'][0]['shipment_status'] ?? "";
                
                $arr_achievement['order_id'] = $order['id'];
                $arr_achievement['shop_id'] = $shop_id;
                $arr_achievement['old_total_price'] = $order['total_price'] ?? 0;
                $arr_achievement['total_price'] = $order['total_price'] ?? 0;
                if($order['financial_status'] == "refunded"){
                    $arr_achievement['total_price'] = 0;
                }
                $arr_achievement['refund'] = 0;
                $arr_achievement['subtotal_price'] = $order['subtotal_price'] ?? 0;
                $arr_achievement['discounted_price'] = 0;
                $arr_achievement['tax_lines'] = 0;
                $arr_achievement['currency'] = $order['currency'] ?? "";
                if (!empty($order['shipping_lines'])) {  
                    foreach ($order['shipping_lines'] as $shippingLine) {  
                        if (isset($shippingLine['discounted_price'])) {  
                            $arr_achievement['discounted_price'] += (float)$shippingLine['discounted_price'];  
                        }  
                        if (isset($shippingLine['tax_lines'])) {  
                            $arr_achievement['tax_lines'] += (float)$shippingLine['tax_lines'];  
                        }  
                    }  
                }
                //第一次存入skuquantity件数
                $arr_achievement['skuquantity'] = (int)$skuinfo['skuquantity']; 
                $arr_achievement['sku'] = $skuinfo['arr_source_skus'] ?? ""; 
                $arr_achievement['spu'] = $skuinfo['arr_source_spus'] ?? ""; 
                $arr_achievement['createtime'] = $this->dateTimeStr($order['created_at']); 
                $arr_achievement['payment_gateway_names'] = $order['payment_gateway_names'][0] ?? ""; 
                $arr_achievement['country_code'] = $order['shipping_address']['country_code'] ?? ""; 
                $arr_achievement['tags'] = $order['tags'] ?? "";
                break;
            case 'update':
                $arr_achievement['name'] = $order['name'] ?? "";
                $arr_achievement['financial_status'] = $order['financial_status'] ?? "";
                $arr_achievement['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                $arr_achievement['tracking_number'] = $order['fulfillments'][0]['tracking_number'] ?? "";
                $arr_achievement['shipment_status'] = $order['fulfillments'][0]['shipment_status'] ?? "";
                $arr_achievement['skuquantity'] = (int)$skuinfo['skuquantity']; 
                $arr_achievement['sku'] = $skuinfo['arr_source_skus'] ?? ""; 
                $arr_achievement['spu'] = $skuinfo['arr_source_spus'] ?? ""; 
                $arr_achievement['tags'] = $order['tags'] ?? "";
                $arr_achievement['old_total_price'] = $order['total_price'] ?? 0;
                $arr_achievement['total_price'] = $order['total_price'] ?? 0;
                $arr_achievement['createtime'] = $this->dateTimeStr($order['created_at']); 
                if($order['financial_status'] == "refunded"){
                    $arr_achievement['total_price'] = 0;
                }
                $arr_achievement['subtotal_price'] = $order['subtotal_price'] ?? 0;
                if (!empty($order['shipping_lines'])) {  
                    $arr_achievement['discounted_price'] = 0;
                    $arr_achievement['tax_lines'] = 0;
                    foreach ($order['shipping_lines'] as $shippingLine) {  
                        if (isset($shippingLine['discounted_price'])) {  
                            $arr_achievement['discounted_price'] += (float)$shippingLine['discounted_price'];  
                        }  
                        if (isset($shippingLine['tax_lines'])) {  
                            $arr_achievement['tax_lines'] += (float)$shippingLine['tax_lines'];  
                        }  
                    }  
                }
                break;
            default:
        }
        
        $order_achievement = Db::name('order_achievement')->where('order_id',$order['id'])->find();
        if(!empty($order_achievement)){
            Db::name('order_achievement')->where('order_id',$order['id'])->update($arr_achievement);
        }else{
            Db::name('order_achievement')->insert($arr_achievement);
        }

        return true;
    }

    /**
    * @desc    order_customer客户
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_customer_handle($order,$shop_id)
    {
        if(isset($order['customer']) && !empty($order['customer'])){
            $customer = $order['customer'];
            $arr_customer['order_id'] = $order['id'];
            $arr_customer['shop_id'] = $shop_id;
            $arr_customer['customer_id'] = $customer['id'];
            $arr_customer['email'] = $customer['email'] ?? "";
            $arr_customer['phone'] = $customer['phone'] ?? "";
            $arr_customer['first_name'] = $customer['first_name'] ?? "";
            $arr_customer['last_name'] = $customer['last_name'] ?? "";
            $arr_customer['state'] = $customer['state'] ?? "";
            $arr_customer['note'] = $customer['note'] ?? "";
            $arr_customer['created_at'] = $customer['created_at'] ?? "";
            $arr_customer['updated_at'] = $customer['updated_at'] ?? "";
            $arr_customer['verified_email'] = $customer['verified_email'] ?? false;
            $arr_customer['tags'] = $customer['tags'] ?? "";
            $arr_customer['accepts_marketing'] = $customer['accepts_marketing'] ?? false;
            $arr_customer['accepts_marketing_updated_at'] = $customer['accepts_marketing_updated_at'] ?? "";
            $arr_customer['email_state'] = $customer['email_marketing_consent']['state'] ?? "";

            $order_customer = Db::name('order_customer')->where('order_id',$order['id'])->find();
            if(!empty($order_customer)){
                Db::name('order_customer')->where('order_id',$order['id'])->update($arr_customer);
            }else{
                Db::name('order_customer')->insert($arr_customer);
            }
        }
        return true;
    }
    
    /**
    * @desc    order_source客户行为日志
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function order_source_handle($order,$shop_id,$skuinfo)
    {
        $arr_source['order_id'] = $order['id']; 
        $arr_source['shop_id'] = $shop_id; 
        $arr_source['name'] = $order['name'] ?? ""; 
        $arr_source['order_number'] = $order['order_number'];
        $arr_source['total_price'] = $order['total_price'] ?? ""; 
        $arr_source['financial_status'] = $order['financial_status'] ?? ""; 
        $arr_source['fulfillment_status'] = $order['fulfillment_status'] ?? ""; 
        $arr_source['createtime'] = $this->dateTimeStr($order['created_at']);
        $arr_source['created_at'] = $order['created_at']; 
        $arr_source['landing_site'] = $order['landing_site'] ?? "";
        $arr_source['tracking_number'] = $order['fulfillments'][0]['tracking_number'] ?? "";
        $arr_source['landing_site'] = $this->removeNonAscii($arr_source['landing_site']);
        $arr_source['referring_site'] = $order['referring_site'] ?? "";
        $arr_source['referring_site'] = $this->removeNonAscii($arr_source['referring_site']);
        $arr_source['tags'] = $order['tags'] ?? "";
        // if(!empty($skuinfo['arr_source_skus'])){
        //     $arr_source['skus'] = implode(',',$skuinfo['arr_source_skus']);
        // }
        //临时情况开始
        if($arr_source['createtime'] > 1703865600){
            $order_source = Db::name('order_source')
                ->where('order_number',$order['order_number'])
                ->where('shop_id',$shop_id)
                ->find();
            if(!empty($order_source)){
                Db::name('order_source')
                    ->where('order_number',$order['order_number'])
                    ->where('shop_id',$shop_id)
                    ->update($arr_source);
            }else{
                Db::name('order_source')->insert($arr_source);
            }
        }
    }
    
    /**
    * @desc    order_fulfillments物流轨迹
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function order_fulfillments_handle($order,$shop_id)
    {
        if($order['fulfillment_status'] == "fulfilled"){
            if(isset($order['fulfillments']) && !empty($order['fulfillments'])){
                $fulfillments = $order['fulfillments'];
                Db::name('order_fulfillments')->where('order_id',$order['id'])->delete();
                foreach ($fulfillments as $fulfillment) {  
                    $arr_fulfillment = [];
                    $arr_fulfillment['order_id'] = $order['id'];
                    $arr_fulfillment['shop_id'] = $shop_id;
                    $arr_fulfillment['name'] = $fulfillment['name'] ?? "";
                    $arr_fulfillment['status'] = $fulfillment['status'] ?? "";
                    $arr_fulfillment['tracking_company'] = $fulfillment['tracking_company'] ?? "";
                    $arr_fulfillment['tracking_number'] = $fulfillment['tracking_number'] ?? "";
                    $arr_fulfillment['tracking_url'] = $fulfillment['tracking_url'] ?? "";
                    $arr_fulfillment['created_at'] = $fulfillment['created_at'] ?? "";
                    $arr_fulfillment['updated_at'] = $fulfillment['updated_at'] ?? "";
                    $arr_fulfillments[] = $arr_fulfillment;

                    //注册物流轨迹
                    //包含4PX不注册
                    // if(strpos($fulfillment['tracking_number'],'4PX') !== false){
                    //     $params = [];
                    //     $params['track_number'] = $fulfillment['tracking_number'];
                    //     (new CheckLogic())->track_4px($params);
                    //     continue;
                    // }
                    // if(strpos($fulfillment['tracking_number'],'DYY') !== false){
                        //发货时间大于8月8日
                    $order_track = Db::name('order_track')->where('track_number',$arr_fulfillment['tracking_number'])->find();
                    if(empty($order_track)){
                        $fulfillment_created_at = $this->dateTimeStr($fulfillment['created_at']); 
                        if($fulfillment_created_at >= 1754582400){ 
                            $this->sync_track_register_718($fulfillment['tracking_number']);
                        }
                    }
                    // continue;

                    // }
                    // $this->sync_track_register($fulfillment['tracking_number']);
                    //注册物流轨迹
                }
                Db::name('order_fulfillments')->insertAll($arr_fulfillments);
            }
        }
        return true;
    }
    
    /**
    * @desc    refunds退款
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_refunds_handle($order,$shop_id)
    {
        // $RefundAmount = 0;
        if(isset($order['refunds']) && !empty($order['refunds'])){
            $refunds = $order['refunds'];
            Db::name('order_refunds')->where('order_id',$order['id'])->delete();
            foreach ($refunds as $refund) {  
                $arr_refund = [];
                $arr_refund['order_id'] = $order['id'];
                $arr_refund['shop_id'] = $shop_id;
                $arr_refund['refund_id'] = $refund['id'];
                $arr_refund['note'] = $refund['note'] ?? "";
                $arr_refund['created_at'] = $refund['created_at'] ?? "";
                $arr_refund['processed_at'] = $refund['processed_at'] ?? "";
                $arr_refunds[] = $arr_refund;

                if(!empty($refund['transactions'])){
                    foreach ($refund['transactions'] as $kt=>$vt) {
                        $arr_transactions = [];
                        $arr_transactions['order_id'] = $order['id'];
                        $arr_transactions['shop_id'] = $shop_id;
                        $arr_transactions['transactions_id'] = $vt['id'];
                        $arr_transactions['status'] = $vt['status'] ?? "";
                        $arr_transactions['gateway'] = $vt['gateway'] ?? "";
                        $arr_transactions['message'] = $vt['message'] ?? "";
                        $arr_transactions['authorization'] = $vt['authorization'] ?? "";
                        $arr_transactions['amount'] = $vt['amount'] ?? "";
                        $arr_transactions['currency'] = $vt['currency'] ?? "";
                        $arr_transactions['payment_id'] = $vt['payment_id'] ?? "";
                        $arr_transactions['kind'] = $vt['kind'] ?? "";
                        $arr_transactions['created_at'] = $vt['created_at'] ?? "";
                        if(!empty($vt['receipt'])){
                            $arr_transactions['parent_txn_id'] = $vt['receipt']['parent_txn_id'] ?? 0;
                        }
                        $arr_transactionss[] = $arr_transactions;
                        //退款金额
                        // $RefundAmount = $RefundAmount + $arr_transactions['amount'];
                        Db::name('order_transactions')->where('transactions_id',$arr_transactions['transactions_id'])->delete();
                    }
                    Db::name('order_transactions')->insertAll($arr_transactionss);
                }
            }
            Db::name('order_refunds')->insertAll($arr_refunds);
        }
        return true;
    }
    
    
    public function removeNonAscii($string) {  
        $output = '';  
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
            $char = mb_substr($string, $i, 1, 'UTF-8');  
            if (ord($char[0]) < 128) {  
                $output .= $char;  
            }  
        }  
        return $output;  
    }  
    

    public function dateTimeStr($dateTimeStr) {  
        $posT = strpos($dateTimeStr, 'T');  
        if ($posT !== false) {  
            $datePart = substr($dateTimeStr, 0, $posT);  
            $timePart = substr($dateTimeStr, $posT + 1, strpos($dateTimeStr, '-', $posT + 1) - ($posT + 1));  
            $formattedDateTime = $datePart . ' ' . $timePart;  
            $formattedDateTime = strtotime($formattedDateTime);
            if (!$formattedDateTime) {  
                $datePart = substr($dateTimeStr, 0, $posT);  
                $timePart = substr($dateTimeStr, $posT + 1, strpos($dateTimeStr, '+', $posT + 1) - ($posT + 1));  
                $formattedDateTime = $datePart . ' ' . $timePart;  
                $formattedDateTime = strtotime($formattedDateTime);
                return $formattedDateTime;
            }else{
                return $formattedDateTime;
            }
        } else {  
            return 0;
        }  
    }

    

// --------------------------------------------------------shopline 

    /**
    * @desc    order_achievement订单金额
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_achievement_handle_shopline($order,$shop_id,$skuinfo,$type)
    {
        switch ($type) {
            case 'insert':
                $arr_achievement['name'] = $order['name'] ?? "";
                $arr_achievement['financial_status'] = $order['financial_status'] ?? "";
                $arr_achievement['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                $arr_achievement['tracking_number'] = $order['fulfillments'][0]['tracking_number'] ?? "";
                $arr_achievement['shipment_status'] = $order['fulfillments'][0]['shipment_status'] ?? "";
                
                $arr_achievement['order_id'] = $order['id'];
                $arr_achievement['shop_id'] = $shop_id;
                $arr_achievement['old_total_price'] = $order['current_total_price'] ?? 0;
                $arr_achievement['total_price'] = $order['current_total_price'] ?? 0;
                if($order['financial_status'] == "refunded"){
                    $arr_achievement['total_price'] = 0;
                }
                $arr_achievement['refund'] = 0;
                $arr_achievement['subtotal_price'] = $order['subtotal_price'] ?? 0;
                $arr_achievement['discounted_price'] = 0;
                $arr_achievement['tax_lines'] = 0;
                $arr_achievement['currency'] = $order['currency'] ?? "";
                if (!empty($order['shipping_lines'])) {  
                    foreach ($order['shipping_lines'] as $shippingLine) {  
                        if (isset($shippingLine['discounted_price'])) {  
                            $arr_achievement['discounted_price'] += (float)$shippingLine['discounted_price'];  
                        } 
                    }  
                }
                //第一次存入skuquantity件数
                $arr_achievement['skuquantity'] = (int)$skuinfo['skuquantity']; 
                $arr_achievement['sku'] = $skuinfo['arr_source_skus'] ?? ""; 
                $arr_achievement['spu'] = $skuinfo['arr_source_spus'] ?? ""; 
                $arr_achievement['createtime'] = $this->dateTimeStr($order['created_at']); 
                $arr_achievement['payment_gateway_names'] = $order['payment_gateway_names'][0] ?? ""; 
                $arr_achievement['country_code'] = $order['shipping_address']['country_code'] ?? ""; 
                $arr_achievement['tags'] = $order['tags'] ?? "";
                break;
            case 'update':
                $arr_achievement['name'] = $order['name'] ?? "";
                $arr_achievement['financial_status'] = $order['financial_status'] ?? "";
                $arr_achievement['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                $arr_achievement['tracking_number'] = $order['fulfillments'][0]['tracking_number'] ?? "";
                $arr_achievement['shipment_status'] = $order['fulfillments'][0]['shipment_status'] ?? "";
                //第一次存入skuquantity件数
                $arr_achievement['skuquantity'] = (int)$skuinfo['skuquantity']; 
                $arr_achievement['sku'] = $skuinfo['arr_source_skus'] ?? ""; 
                $arr_achievement['spu'] = $skuinfo['arr_source_spus'] ?? ""; 
                $arr_achievement['tags'] = $order['tags'] ?? "";
                $arr_achievement['old_total_price'] = $order['current_total_price'] ?? 0;
                $arr_achievement['total_price'] = $order['current_total_price'] ?? 0;
                $arr_achievement['createtime'] = $this->dateTimeStr($order['created_at']); 
                if($order['financial_status'] == "refunded"){
                    $arr_achievement['total_price'] = 0;
                }
                $arr_achievement['subtotal_price'] = $order['subtotal_price'] ?? 0;
                $arr_achievement['discounted_price'] = 0;
                $arr_achievement['tax_lines'] = 0;
                $arr_achievement['currency'] = $order['currency'] ?? "";
                if (!empty($order['shipping_lines'])) {  
                    foreach ($order['shipping_lines'] as $shippingLine) {  
                        if (isset($shippingLine['discounted_price'])) {  
                            $arr_achievement['discounted_price'] += (float)$shippingLine['discounted_price'];  
                        } 
                    }  
                }
                break;
            default:
        }
        
        $order_achievement = Db::name('order_achievement')->where('order_id',$order['id'])->find();
        if(!empty($order_achievement)){
            Db::name('order_achievement')->where('order_id',$order['id'])->update($arr_achievement);
        }else{
            Db::name('order_achievement')->insert($arr_achievement);
        }

        return true;
    }

    
    
    /**
    * @desc    订单主表
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_handle_shopline($order,$shop_id,$type)
    {
        switch ($type) {
            case 'insert':
                $insert = [
                    'order_id' => $order['id'],
                    'shop_id' => $shop_id,
                    'name' => $order['name'],
                    'number' => $order['name'],
                    'order_number' => $order['name'],
                    'total_price' => $order['current_total_price'],
                    'currency' => $order['currency'] ?? "",
                    'financial_status' => $order['financial_status'] ?? "",
                    'fulfillment_status' => $order['fulfillment_status'] ?? "",
                    'tracking_number' => $order['fulfillments'][0]['tracking_number'] ?? "",
                    'created_at' => $order['created_at'],
                    'updated_at' => $order['updated_at'],
                    'closed_at' => $order['cancelled_at'] ?? "",
                    'createtime' => $this->dateTimeStr($order['created_at']),
                    'updatetime' => $this->dateTimeStr($order['updated_at']),
                    'payment_gateway_names' => $order['payment_gateway_names'][0] ?? "",
                    'country_code' => $order['shipping_address']['country_code'] ?? "",
                ];
                break;
            case 'update':
                $insert = [
                    'total_price' => $order['current_total_price'],
                    'financial_status' => $order['financial_status'] ?? "",
                    'fulfillment_status' => $order['fulfillment_status'] ?? "",
                    'tracking_number' => $order['fulfillments'][0]['tracking_number'] ?? "",
                    'closed_at' => $order['closed_at'] ?? "",
                    'updated_at' => $order['updated_at'],
                ];
                break;
            default:
        }
        $orderdb = Db::name('order')->where('order_id',$order['id'])->find();
        if(!empty($orderdb)){
            Db::name('order')->where('order_id',$order['id'])->update($insert);
        }else{
            Db::name('order')->insert($insert);
        }
        return true;
    }
    /**
    * @desc    order_info订单详情
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_info_handle_shopline($order,$shop_id)
    {
        $skuquantity = 0;
        $arr_source_skus = [];
        $arr_source_spus = [];

        if(isset($order['line_items']) && !empty($order['line_items'])){
            $line_items = $order['line_items'];
            Db::name('order_skuinfo')->where('order_id',$order['id'])->delete();
            foreach ($line_items as $line_item) {  
                $arr_info = [];
                $arr_info['order_id'] = $order['id'];
                $arr_info['shop_id'] = $shop_id;
                $arr_info['info_id'] = $line_item['id'];
                $arr_info['product_id'] = $line_item['product_id'] ?? "";
                $arr_info['name'] = $line_item['name'] ?? "";
                $arr_info['name'] = $this->removeNonAscii($arr_info['name']);
                $arr_info['variant_id'] = $line_item['variant_id'] ?? "";
                $arr_info['sku'] = $line_item['sku'] ?? "";

                $arr_info['created_at'] = $order['created_at'];
                $arr_info['updated_at'] = $order['updated_at'];
                
                //订单详情加spu
                $arr_info['spu'] = "";
                $dashPos = strpos($arr_info['sku'], '-');  
                if ($dashPos !== false) {  
                    $arr_info['spu'] = substr($arr_info['sku'], 0, $dashPos);  
                }

                $arr_info['variant_title'] = $line_item['variant_title'] ?? "";
                $arr_info['variant_title'] = $this->removeNonAscii($arr_info['variant_title']);
                $arr_info['quantity'] = $line_item['quantity'] ?? "";
                $arr_info['price'] = $line_item['price'] ?? 0;
                //统计件数
                $skuquantity = $skuquantity + $this->CountTheNumberOfItems($arr_info,$order);
                //skus集合
                if(!empty($arr_info['sku'])){
                    $arr_source_skus[] = $arr_info['sku'];
                }
                if(!empty($arr_info['spu'])){
                    $arr_source_spus[] = $arr_info['spu'];
                }

                $order_info = Db::name('order_info')->where('info_id',$arr_info['info_id'])->find();
                if(!empty($order_info)){
                    Db::name('order_info')->where('info_id',$arr_info['info_id'])->update($arr_info);
                }else{
                    Db::name('order_info')->insert($arr_info);
                }

            }
            
        }
        $arr_source_skus = array_unique($arr_source_skus);
        if(!empty($arr_source_skus)){
            $arr_source_skus = implode(',',$arr_source_skus);
        }else{
            $arr_source_skus = '';
        }
        $arr_source_spus = array_unique($arr_source_spus);
        if(!empty($arr_source_spus)){
            $arr_source_spus = implode(',',$arr_source_spus);
        }else{
            $arr_source_spus = '';
        }
        
        $skuinfo = [
            'arr_source_skus' => $arr_source_skus,
            'arr_source_spus' => $arr_source_spus,
            'skuquantity' => $skuquantity,
        ];
        return $skuinfo;
    }
    
    /**
    * @desc    order_customer客户
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_customer_handle_shopline($order,$shop_id)
    {
        if(isset($order['customer']) && !empty($order['customer'])){
            $customer = $order['customer'];
            $arr_customer['order_id'] = $order['id'];
            $arr_customer['shop_id'] = $shop_id;
            $arr_customer['customer_id'] = $customer['id'];
            $arr_customer['email'] = $customer['email'] ?? "";
            $arr_customer['phone'] = $customer['phone'] ?? "";
            $arr_customer['first_name'] = $customer['first_name'] ?? "";
            $arr_customer['last_name'] = $customer['last_name'] ?? "";
            $arr_customer['created_at'] = $customer['created_at'] ?? "";
            $arr_customer['updated_at'] = $customer['updated_at'] ?? "";
            $arr_customer['email_state'] = $customer['email_marketing_consent']['state'] ?? "";

            $order_customer = Db::name('order_customer')->where('order_id',$order['id'])->find();
            if(!empty($order_customer)){
                Db::name('order_customer')->where('order_id',$order['id'])->update($arr_customer);
            }else{
                Db::name('order_customer')->insert($arr_customer);
            }
        }
        return true;
    }
    /**
    * @desc    order_source客户行为日志
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function order_source_handle_shopline($order,$shop_id,$skuinfo)
    {
        $arr_source['order_id'] = $order['id']; 
        $arr_source['shop_id'] = $shop_id; 
        $arr_source['name'] = $order['name'] ?? ""; 
        $arr_source['order_number'] = $order['name'];
        $arr_source['total_price'] = $order['current_total_price'] ?? ""; 
        $arr_source['financial_status'] = $order['financial_status'] ?? ""; 
        $arr_source['fulfillment_status'] = $order['fulfillment_status'] ?? ""; 
        $arr_source['createtime'] = $this->dateTimeStr($order['created_at']);
        $arr_source['created_at'] = $order['created_at']; 
        $arr_source['landing_site'] = $order['landing_site'] ?? "";
        $arr_source['tracking_number'] = $order['fulfillments'][0]['tracking_number'] ?? "";
        $arr_source['landing_site'] = $this->removeNonAscii($arr_source['landing_site']);
        $arr_source['referring_site'] = $order['referring_site'] ?? "";
        $arr_source['referring_site'] = $this->removeNonAscii($arr_source['referring_site']);
        $arr_source['tags'] = $order['tags'] ?? "";
        // if(!empty($skuinfo['arr_source_skus'])){
        //     $arr_source['skus'] = implode(',',$skuinfo['arr_source_skus']);
        // }
        //临时情况开始
        if($arr_source['createtime'] > 1703865600){
            $order_source = Db::name('order_source')
                ->where('name',$order['name'])
                ->where('shop_id',$shop_id)
                ->find();
            if(!empty($order_source)){
                Db::name('order_source')
                    ->where('name',$order['name'])
                    ->where('shop_id',$shop_id)
                    ->update($arr_source);
            }else{
                Db::name('order_source')->insert($arr_source);
            }
        }
    }

    
    /**
    * @desc    order_fulfillments物流轨迹
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function order_fulfillments_handle_shopline($order,$shop_id)
    {
        if($order['fulfillment_status'] == "fulfilled"){
            if(isset($order['fulfillments']) && !empty($order['fulfillments'])){
                $fulfillments = $order['fulfillments'];
                Db::name('order_fulfillments')->where('order_id',$order['id'])->delete();
                foreach ($fulfillments as $fulfillment) {  
                    $arr_fulfillment = [];
                    $arr_fulfillment['order_id'] = $order['id'];
                    $arr_fulfillment['shop_id'] = $shop_id;
                    $arr_fulfillment['name'] = $fulfillment['name'] ?? "";
                    $arr_fulfillment['status'] = $fulfillment['status'] ?? "";
                    $arr_fulfillment['tracking_company'] = $fulfillment['tracking_company'] ?? "";
                    $arr_fulfillment['tracking_number'] = $fulfillment['tracking_number'] ?? "";
                    $arr_fulfillment['tracking_url'] = $fulfillment['tracking_url'] ?? "";
                    $arr_fulfillment['created_at'] = $fulfillment['created_at'] ?? "";
                    $arr_fulfillment['updated_at'] = $fulfillment['updated_at'] ?? "";
                    $arr_fulfillments[] = $arr_fulfillment;

                    //注册物流轨迹
                    //包含4PX不注册
                    // if(strpos($fulfillment['tracking_number'],'4PX') !== false){
                    //     $params = [];
                    //     $params['track_number'] = $fulfillment['tracking_number'];
                    //     (new CheckLogic())->track_4px($params);
                    //     continue;
                    // }
                    // if(strpos($fulfillment['tracking_number'],'DYY') !== false){
                    //发货时间大于8月8日
                    $order_track = Db::name('order_track')->where('track_number',$arr_fulfillment['tracking_number'])->find();
                    if(empty($order_track)){
                        $fulfillment_created_at = $this->dateTimeStr($fulfillment['created_at']); 
                        if($fulfillment_created_at >= 1754582400){ 
                            $this->sync_track_register_718($fulfillment['tracking_number']);
                        }
                    }
                    //     continue;
                    // }
                    // $this->sync_track_register($fulfillment['tracking_number']);
                    //注册物流轨迹
                }
                Db::name('order_fulfillments')->insertAll($arr_fulfillments);
            }
        }
        return true;
    }
    
    /**
    * @desc    refunds退款
    * @date    2024/7/31
    * @author  zhangheng
    */
    public function order_refunds_handle_shopline($order,$shop_id)
    {
        // $RefundAmount = 0;
        if(isset($order['refunds']) && !empty($order['refunds'])){
            $refunds = $order['refunds'];
            Db::name('order_refunds')->where('order_id',$order['id'])->delete();
            foreach ($refunds as $refund) {  
                $arr_refund = [];
                $arr_refund['order_id'] = $order['id'];
                $arr_refund['shop_id'] = $shop_id;
                // $arr_refund['refund_id'] = $refund['id'];
                // $arr_refund['note'] = $refund['note'] ?? "";
                // $arr_refund['created_at'] = $refund['created_at'] ?? "";
                // $arr_refund['processed_at'] = $refund['processed_at'] ?? "";
                $arr_refunds[] = $arr_refund;

                // if(!empty($refund['transactions'])){
                //     foreach ($refund['transactions'] as $kt=>$vt) {
                //         $arr_transactions = [];
                //         $arr_transactions['order_id'] = $order['id'];
                //         $arr_transactions['shop_id'] = $shop_id;
                //         $arr_transactions['transactions_id'] = $vt['id'];
                //         $arr_transactions['status'] = $vt['status'] ?? "";
                //         $arr_transactions['gateway'] = $vt['gateway'] ?? "";
                //         $arr_transactions['message'] = $vt['message'] ?? "";
                //         $arr_transactions['authorization'] = $vt['authorization'] ?? "";
                //         $arr_transactions['amount'] = $vt['amount'] ?? "";
                //         $arr_transactions['currency'] = $vt['currency'] ?? "";
                //         $arr_transactions['payment_id'] = $vt['payment_id'] ?? "";
                //         $arr_transactions['kind'] = $vt['kind'] ?? "";
                //         $arr_transactions['created_at'] = $vt['created_at'] ?? "";
                //         if(!empty($vt['receipt'])){
                //             $arr_transactions['parent_txn_id'] = $vt['receipt']['parent_txn_id'] ?? 0;
                //         }
                //         $arr_transactionss[] = $arr_transactions;
                //         //退款金额
                //         // $RefundAmount = $RefundAmount + $arr_transactions['amount'];
                //         Db::name('order_transactions')->where('transactions_id',$arr_transactions['transactions_id'])->delete();
                //     }
                //     Db::name('order_transactions')->insertAll($arr_transactionss);
                // }
            }
            Db::name('order_refunds')->insertAll($arr_refunds);
        }
        return true;
    }

// --------------------------------------------------------shopline
    /**
    * 手动发货
    * @param array params
    */
    public function ManualShippings($params)
    {
        $data['order_id'] = $params['order_id'] ?? "6486680240439";
        $data['number'] = $params['number'] ?? "4PX3001797638152CN";
        $data['shop_id'] = $params['shop_id'] ?? "23";
        return $this->ManualShipping($data);
    }

    /**
    * 创建事件
     * https://shopify.fan-zhou.com/api/ApiOrder/CreateEvent?order_id=6496163070263&shop_id=23&status=confirmed
    * @param array params
    */
    public function CreateEvent($data)
    {
        if(empty($data['order_id'])){
            return json(DefaultResponse(200, true, '订单号order_id为空', ''));
        }
        $order_id = $data['order_id'];
        $shop_id = $data['shop_id'] ?? 0;
        $status = $data['status'] ?? 'in_transit';

        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();

        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments.json";
        $fulfillments = HttpUtil::getUrl($url, $shop_info);
        // halt($fulfillments);
        $fulfillment_id = $fulfillments['fulfillments'][0]['id'] ?? 0;
        if($fulfillment_id == 0){
            return json(DefaultResponse(200, true, '没有可发货的订单', ''));
        }
        //物流详情
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments/".$fulfillment_id."/events.json";
        //新增
        $data_fulfillment = [];
        $data_fulfillment['status'] = $status;
        $data_fulfillments = [
            'event' => $data_fulfillment
        ];
        $return = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
        halt($return);
        
    }
    
    /**
     * @desc 手动发货
     * @date   2024-07-09
     */
    public function ManualShipping($data=[]){
        if(empty($data['order_id'])){
            return json(DefaultResponse(200, true, '订单号order_id为空', ''));
        }
        if(empty($data['number'])){
            return json(DefaultResponse(200, true, '物流单号number为空', ''));
        }
        
        $order_id = $data['order_id'];
        $number = $data['number'];
        $shop_id = $data['shop_id'] ?? 0;

        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        
        // 详情
        // $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id.".json";
        // $orders = HttpUtil::getUrl($url, $shop_info);
        // halt($orders);

        //物流详情
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments/5762759393591/events.json";
        //新增
        $data_fulfillments = [];
        $data_fulfillments4 = [];
        $data_fulfillments4['status'] = "in_transit";
        $data_fulfillments['event'] = $data_fulfillments4;
        $return = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
        halt($return);
        $fulfillments = HttpUtil::getUrl($url, $shop_info);
        halt($fulfillments);

        //关闭物流        
        // $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/fulfillments/11111111111111111/cancel.json";
        // $data_fulfillments['fulfillment_id'] = 11111111111111111;
        // $return1 = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
        // halt($return1);

        //获取履行订单id
        $fulfillment_order_id = 0;

        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillment_orders.json";
        $fulfillment_orders = HttpUtil::getUrl($url, $shop_info);
        // halt($fulfillment_orders);
        
        if(!empty($fulfillment_orders['fulfillment_orders'][0]['id']) && isset($fulfillment_orders['fulfillment_orders'][0]['id'])){
            $fulfillment_order_id = $fulfillment_orders['fulfillment_orders'][0]['id'];
        }
        if(!empty($fulfillment_order_id)){
            //创建事件
            $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/6496163070263/fulfillments/7501630964023/events.json";
            $data_fulfillments4 = [];
            $data_fulfillments4['status'] = "in_transit";
            $data_fulfillments['event'] = $data_fulfillments4;
            $return = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
            halt($return);
            //创建事件


            //物流id
            $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/fulfillments.json";
            $data_fulfillments3['notify_customer'] = false;
            $data_fulfillments3['tracking_info']['company'] = "4PX";
            $data_fulfillments3['tracking_info']['number'] = $number;
            $data_fulfillments3['line_items_by_fulfillment_order'][0]['fulfillment_order_id'] = $fulfillment_order_id;
            $data_fulfillments['fulfillment'] = $data_fulfillments3;
            $return = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
            halt($return);
            
            $return = json_decode($return, true);
            if(!empty($return['errors']) || !empty($return['error'])){
                return json(DefaultResponse(200, true, '发货失败', ''));
            }else{
                return json(DefaultResponse(200, true, '发货成功', ''));
            }
        }
        return json(DefaultResponse(200, true, '没有物流信息', ''));
    }


    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 整理每日订单统计
     * @author zhangheng
     */
    public function OrderReportDaily($params = [])
    {
        //订单时间createtime是美国时间

        //每天4点转点开始计算昨天的数据
        $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());  
        // 然后计算昨天凌晨的时间戳  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');

        $where = [];
        $where[]  = ['a.createtime', '>=', $midnightYesterday];
        $where[]  = ['a.createtime', '<=', $endOfYesterday];
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $lists = Db::name('order_achievement')
            ->field('COUNT(a.id) as quantity,sum(a.total_price) as total_price,a.shop_id,a.currency,b.name as shop_name,sum(a.skuquantity) as skuquantity')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->where($where)
            ->group('a.shop_id')
            ->select()
            ->toarray();

        if(!empty($lists)){
            foreach ($lists as $k=>$v) {
                
                $v['date'] = date('Y-m-d', $midnightYesterday);  
                $v['timestamp'] = $midnightYesterday;  
                //预估物流
                $v['freight'] = (float)number_format((float)$v['total_price'] * 0.06, 3, '.', '');
                //预估采购
                $v['material'] = (float)number_format((float)$v['total_price'] * 0.06, 3, '.', '');
                //广告费
                $v['advertising'] = 0;
                //退款
                $v['refund'] = (float)number_format((float)$v['total_price'] * 0.02, 3, '.', '');
                //ROI
                if ($v['advertising'] > 0.001 && $v['total_price'] > 0.001) {
                    $v['roi'] = number_format((float)$v['total_price'] / (float)$v['advertising'], 3, '.', '');
                }else{
                    $v['roi'] = 0;
                }

                //盈利
                $v['profit'] = number_format((float)$v['total_price'] - (float)$v['advertising'] - (float)$v['freight'] - (float)$v['material'] - (float)$v['refund'], 3, '.', '');

                $order_report_daily = Db::name('order_report_daily')
                    ->where('shop_id',$v['shop_id'])
                    ->where('timestamp',$midnightYesterday)
                    ->find();
                    
                if(!empty($order_report_daily)){
                    $order_report_daily = Db::name('order_report_daily')
                        ->where('shop_id',$v['shop_id'])
                        ->where('timestamp',$midnightYesterday)
                        ->update($v);
                }else{
                    $order_report_daily = Db::name('order_report_daily')
                    ->insert($v);
                }
            }
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 整理每日SKU统计
     * @author zhangheng
     */
    public function OrderReportDailySku($params = [])
    {
        //订单时间createtime是美国时间

        //每天4点转点开始计算昨天的数据
        $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());  
        // 然后计算昨天凌晨的时间戳  
        $midnightYesterday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($yesterday . ' 23:59:59');

        $where = [];
        $where[]  = ['c.createtime', '>=', $midnightYesterday];
        $where[]  = ['c.createtime', '<=', $endOfYesterday];
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $lists = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as skuquantity,
                spu,
                new_sku as sku
            ')
            ->alias('a')
            ->join('qu_order_achievement c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.new_sku')
            ->select()
            ->toarray();

        if(!empty($lists)){
            foreach ($lists as &$v) { 
                $v['date'] = date('Y-m-d', $midnightYesterday);  
                $v['timestamp'] = $midnightYesterday;  
            }
            Db::name('order_report_sku')
                ->where('timestamp',$midnightYesterday)
                ->delete();
            Db::name('order_report_sku')->insertAll($lists);
        }
        return json(DefaultResponse(200, true, '操作成功', ''));
    }

    /**
    * 统计件数
    * @param array params
    */
    public function CountTheNumberOfItems($arr_info,$order)
    {
        $Number = 0;
        $sku = $arr_info['sku'];
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                //数量
                $km = count($sku) - 1;
                $numeric = is_numeric($sku[$km]) ? true : false;
                if($numeric){
                    //是数字并且小于100才计算数量
                    if($sku[$km] < 25){
                        $Number = $sku[$km];
                    }else{
                        $Number = 1;
                    }
                }else{
                    $Number = 1;
                }
                
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);

                    //存入到sku明细中---开始
                    $order_skuinfo_arrs = [];
                    foreach ($skuPlus as $vp) {
                        $order_skuinfo_arr = [];
                        $order_skuinfo_arr['shop_id'] = $arr_info['shop_id'];
                        $order_skuinfo_arr['order_id'] = $arr_info['order_id'];
                        $order_skuinfo_arr['product_id'] = $arr_info['product_id'];
                        $order_skuinfo_arr['sku_id'] = $arr_info['variant_id'];
                        $order_skuinfo_arr['sku'] = $arr_info['sku'];
                        $order_skuinfo_arr['spu'] = $sku[0];
                        $order_skuinfo_arr['count'] = $Number;
                        $order_skuinfo_arr['create_time'] = date("Y-m-d H:i:s");

                        //新增字段
                        $order_skuinfo_arr['financial_status'] = $order['financial_status'] ?? "";
                        $order_skuinfo_arr['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                        $order_skuinfo_arr['createtime'] = $this->dateTimeStr($order['created_at']); 

                        if($arr_info['sku']=='SEEL-WFP'){
                            $order_skuinfo_arr['is_seel'] = 1;
                        }
                        //真实件数
                        if($Number >= 1 && $arr_info['quantity'] >= 1){
                            $order_skuinfo_arr['realcount'] = (int)number_format((int)$arr_info['quantity']*(int)$Number, 3, '.', '');
                        }
                        if(isset($sku[2]) && !empty($sku[2])){
                            $order_skuinfo_arr['new_sku'] = $sku[0].'-'.$vp.'-'.$sku[2];
                        }else{
                            $order_skuinfo_arr['new_sku'] = $sku[0].'-'.$vp;
                        }
                        $order_skuinfo_arrs[] = $order_skuinfo_arr;
                    }
                    if(!empty($order_skuinfo_arrs)){
                        Db::name('order_skuinfo')->insertAll($order_skuinfo_arrs);
                    }
                    //存入到sku明细中---结束
                    
                    $kmPlus = count($skuPlus);
                    if($kmPlus >= 1){
                        $Number = $Number * $kmPlus;
                    }
                }else{
                    
                    // 存入到sku明细中---开始
                    $order_skuinfo_arr = [];
                    $order_skuinfo_arr['shop_id'] = $arr_info['shop_id'];
                    $order_skuinfo_arr['order_id'] = $arr_info['order_id'];
                    $order_skuinfo_arr['product_id'] = $arr_info['product_id'];
                    $order_skuinfo_arr['sku_id'] = $arr_info['variant_id'];
                    $order_skuinfo_arr['sku'] = $arr_info['sku'];
                    $order_skuinfo_arr['spu'] = $sku[0];
                    $order_skuinfo_arr['count'] = $Number;
                    $order_skuinfo_arr['create_time'] = date("Y-m-d H:i:s");

                    //新增字段
                    $order_skuinfo_arr['financial_status'] = $order['financial_status'] ?? "";
                    $order_skuinfo_arr['fulfillment_status'] = $order['fulfillment_status'] ?? "";
                    $order_skuinfo_arr['createtime'] = $this->dateTimeStr($order['created_at']); 

                    if($arr_info['sku']=='SEEL-WFP'){
                        $order_skuinfo_arr['is_seel'] = 1;
                    }
                    //真实件数
                    if($Number >= 1 && $arr_info['quantity'] >= 1){
                        $order_skuinfo_arr['realcount'] = (int)number_format((int)$arr_info['quantity']*(int)$Number, 3, '.', '');
                    }
                    if(isset($sku[2]) && !empty($sku[2])){
                        $order_skuinfo_arr['new_sku'] = $sku[0].'-'.$sku[1].'-'.$sku[2];
                    }else{
                        $order_skuinfo_arr['new_sku'] = $sku[0].'-'.$sku[1];
                    }
                    Db::name('order_skuinfo')->insert($order_skuinfo_arr);
                    // 存入到sku明细中---结束

                }
            }
        }
        if($Number >= 1 && $arr_info['quantity'] >= 1){
            $Number = (int)number_format((int)$arr_info['quantity']*(int)$Number, 3, '.', '');
        }
        return $Number;
    }
    

    /**
    * @desc    创建webhook
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function CreateWebhook($params)
    {
        //1创建 2修改 3删除
        $type = 1;
        $shop_id        = $params['shop_id'] ?? 0;

        //店铺
        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks.json";
        
        switch ($type) {
            case '1':
                //创建之前先删除
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks.json";
                $return = HttpUtil::getUrl($url, $shop_info);
                if(empty($return['webhooks'])){
                    halt("无需创建");
                }
                if(!empty($return['webhooks'])){
                    $webhooks = $return['webhooks'];
                    foreach ($webhooks as $k=>$v) {
                        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks/".$v['id'].".json";
                        HttpUtil::delUrl($url,$shop_info);
                    }
                }
               //订单创建
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks.json";
                $post = [];
                $post['webhook']['format'] = "json";
                $post['webhook']['address'] = "https://shopify.fan-zhou.com/api/Webhook/orders_create?shop_id=".$shop_id;
                $post['webhook']['topic'] = "orders/create";
                $return = HttpUtil::PostUrl($url,$post, $shop_info);
                //订单更新
                //订单更新
                $post = [];
                $post['webhook']['format'] = "json";
                $post['webhook']['address'] = "https://shopify.fan-zhou.com/api/Webhook/orders_updated?shop_id=".$shop_id;
                $post['webhook']['topic'] = "orders/updated";
                $return = HttpUtil::PostUrl($url,$post, $shop_info);
                break;
            case '2':
                //修改webhook
                $post = [];
                $post['webhook']['address'] = "https://shopify.fan-zhou.com/api/Webhook/orders_updated?shop_id=".$shop_id;
                $post['webhook']['id'] = "1267232374845";
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks/1546734371100.json";
                $return = HttpUtil::putUrl($url,$post, $shop_info);
                // 修改webhook
                break;
            case '3':
                // 删除webhook
                $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks/1273524027453.json";
                $return = HttpUtil::delUrl($url,$shop_info);
                // 删除webhook
                break; 
            default:
        }
        halt($return);
        return json(DefaultResponse(200, true, '创建成功', $return));
    }

    /**
    * @desc    创建产品webhook
    * @date    2024/11/22
    * @author  zhangheng
    */
    public function CreateProductWebhook($params)
    {
        $shop_id        = $params['shop_id'] ?? 0;
        //店铺
        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        //产品创建
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks.json";
        $post = [];
        $post['webhook']['format'] = "json";
        $post['webhook']['address'] = "https://shopify.fan-zhou.com/api/Webhook/products_create?shop_id=".$shop_id;
        $post['webhook']['topic'] = "products/create";
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        //产品更新
        //产品更新
        $post = [];
        $post['webhook']['format'] = "json";
        $post['webhook']['address'] = "https://shopify.fan-zhou.com/api/Webhook/products_updated?shop_id=".$shop_id;
        $post['webhook']['topic'] = "products/update";
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        halt($return);
        return json(DefaultResponse(200, true, '创建成功', $return));
    }
    
    /**
    * @desc    webhook列表
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function WebhookList($params)
    {
        $shop_id        = $params['shop_id'] ?? 0;
        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/webhooks.json";
        $return = HttpUtil::getUrl($url, $shop_info);
        halt($return);
        return json(DefaultResponse(200, true, '创建成功', $return));
    }


    /**
    * 4点转点之后
    * @param array params
    */
    public function PlugCustomerBehaviorLog()
    {

        $start_at = "2025-05-01 00:00:01";
        $end_at = "2025-06-01 23:59:59";
        $page = Cache::store('redis')->get('order_source_automatic_'.$start_at);
        if($page == "-1"){
            return  $this->jsonMessage(200,true,'操作成功',$page);
        }else{
            if(empty($page)){
                $page = 1;
            }
            $time = array();
            $time['start_at']= $start_at;
            $time['end_at']= $end_at;
            $msg = $this->list($page,$time);
            return  $this->jsonMessage(200,true,'操作成功',['page'=>$page,'msg'=>$msg]);
        }
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function list($page,$time)
    {
        $data = array();
        $data['direction'] = "desc";
        $data['page'] = $page;
        $data['page_size'] = 20;
        $data['shop_ids'] = 58760331325;
        $data['timezone'] = "America/Los_Angeles";
        $data['sort'] = "created_at";
        $data['start_at'] = $time['start_at'];
        $data['end_at'] = $time['end_at'];
        $url = "https://shpf.api.attribuly.com/v1-3/orders/order-list";
        //17号店铺密码
        $token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHBpcmVzX2F0IjoiMjAyNS0wNy0xOSAxNDowMTowMyIsInN1YiI6IjEwOTI5OCIsInRlYW1faWQiOiIxMDQ2MDkiLCJ1c2VyX2lkIjoiMTA5Mjk4In0.yi6kMgF4834PtMnwN7EYMOxdYcLxsY0EFTQDWkKvsYM";
        $return0 = HttpUtil::PostUrlShpf($url,$token,$data);
        $return = json_decode($return0, true);
        // halt($return);
        if(!empty($return['data']['records']) && isset($return['data']['records'])){
            //添加
            $records = $return['data']['records'];
            foreach ($records as $k=>$v) {
                $insert = array();
                $insert['order_number'] = $v['order_number'];
                $insert['shop_id'] = 17;
                $insert['plug_status'] = 1;
                // $insert['order_id'] = "";
                $insert['first_source'] = "";
                $insert['first_campaign'] = "";
                $insert['last_source'] = "";
                $insert['last_campaign'] = "";
                if(!empty($v['event']['first_event']) && isset($v['event']['first_event'])){
                    $first_event = $v['event']['first_event'];
                    $insert['first_source'] = $first_event['dm_source'];
                    $insert['first_campaign'] = $this->removeEmojis($first_event['dm_campaign']);
                }
                if(!empty($v['event']['last_event']) && isset($v['event']['last_event'])){
                    $last_event = $v['event']['last_event'];
                    $insert['last_source'] = $last_event['dm_source'];
                    $insert['last_campaign'] = $this->removeEmojis($last_event['dm_campaign']);
                }
                $order_source = Db::name('order_source')
                    ->where('shop_id',17)
                    ->where('order_number',$insert['order_number'])
                    ->find();
                if(!empty($order_source)){
                    $return = Db::name('order_source')
                        ->where('shop_id',17)
                        ->where('order_number',$insert['order_number'])
                        ->update($insert);
                }else{
                    // $return = Db::name('order_source')->insert($insert);
                }
            }
                $page = $page + 1;
                Cache::store('redis')->set('order_source_automatic_'.$time['start_at'], $page, 3600 * 24);
                return "下一页";
        }else{
            Cache::store('redis')->set('order_source_automatic_'.$time['start_at'], -1, 3600 * 24 * 3);
            return "完成";
        }
    }

    function removeEmojis($string) {
        $regex = '/[\x{1F600}-\x{1F64F}]|[\x{1F300}-\x{1F5FF}]|[\x{1F680}-\x{1F6FF}]|[\x{1F700}-\x{1F77F}]|[\x{1F780}-\x{1F7FF}]|[\x{1F800}-\x{1F8FF}]|[\x{1F900}-\x{1F9FF}]|[\x{1FA00}-\x{1FA6F}]|[\x{2600}-\x{26FF}]|[\x{2700}-\x{27BF}]|\p{So}/u';
        return preg_replace($regex, '', $string);
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function customerj_handle()
    {
        // $update['status'] = 0;
        // $update['graphql_status'] = 1;
        // $update['plug_status'] = 1;
        // $counts = Db::name('order_source')
        //     ->where('createtime',">=",1725120000)
        //     ->where('createtime',"<=",1727712000)
        //     ->where('tag_source',"=","LabelIsEmpty")
        //     ->order('order_number asc')
        //     ->update($update);
        //     halt($counts);
            
        $customerjourneys = Db::name('order_source')
            ->where('status',0)
            ->where('createtime',">=",1727712000)
            ->where('createtime',"<=",1730390400)
            // ->where('graphql_status',1)
            // ->where('plug_status',1)
            ->order('order_number asc')
            // ->count();
            ->limit(10)
            ->select()->toarray();
            // halt($customerjourneys);
        foreach ($customerjourneys as $k=>$customerjourney) {
            $order_source = $this->customerjourney($customerjourney);
            //自动补全渠道标签
            if($order_source['tag_source'] == "LabelIsEmpty" && $order_source['tag_campaign'] !== "LabelIsEmpty"){
                $order_source['tag_source'] = $this->tag_campaign_tag($order_source["tag_campaign"]);
            }
            $update = [];
            $update["tag_source"] = $order_source['tag_source'];
            $update["tag_campaign"] = $order_source['tag_campaign'];
            $update['status'] = 1;
            if($update["tag_source"] == "other"){
                $update['status'] = 2;
            }
            Db::name('order_source')
                ->where('id',$customerjourney['id'])
                ->update($update);
                
        }
        return success("完成");
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function customerjourney($customerjourney)
    {
        $customerjourneys['tag_source'] = "LabelIsEmpty";
        $customerjourneys['tag_campaign'] = "LabelIsEmpty";
        //新规则 6月6
        if(!empty($customerjourney['lastVisit_campaign']) && !empty($customerjourney['landing_site'])){
            $tag_campaign = $this->tag_campaign($customerjourney['lastVisit_campaign']);
            if($tag_campaign !== "LabelIsEmpty"){
                $pos = strpos($customerjourney['landing_site'], $tag_campaign);
                if ($pos !== false) {
                    $customerjourneys['tag_source'] = $this->tag_campaign_tag($customerjourney['lastVisit_campaign']);
                    $customerjourneys['tag_campaign'] = $tag_campaign;
                    return $customerjourneys;
                }
            }
        }
        if(!empty($customerjourney['lastVisit_campaign'])){
            $tag_campaign = $this->tag_campaign($customerjourney['lastVisit_campaign']);
            if($tag_campaign !== "LabelIsEmpty"){
                $customerjourneys['tag_source'] = $this->tag_campaign_tag($customerjourney['lastVisit_campaign']);
                $customerjourneys['tag_campaign'] = $tag_campaign;
                return $customerjourneys;
            }
        }
        //情况3 只有landing_site有数据
        if(!empty($customerjourney['landing_site'])){
            $tag_campaign = $this->tag_landing_site($customerjourney['landing_site']);
            if($tag_campaign !== "LabelIsEmpty"){
                $customerjourneys['tag_source'] = $this->tag_campaign_tag($tag_campaign);
                $customerjourneys['tag_campaign'] = $tag_campaign;
                return $customerjourneys;
            }
        }
        if(!empty($customerjourney['landing_site'])){
            $tag_source = $this->tag_site($customerjourney['landing_site']);
            if($tag_source !== "LabelIsEmpty"){
                $customerjourneys['tag_source'] = $tag_source;
                //0614补充
                $customerjourneys['tag_campaign'] = "LabelIsEmpty";
                if(!empty($customerjourney['lastVisit_campaign']) && $customerjourneys['tag_campaign'] == "LabelIsEmpty"){
                    $tag_campaign = $this->tag_campaign($customerjourney['lastVisit_campaign']);
                    if($tag_campaign !== "LabelIsEmpty"){
                        $customerjourneys_tag_source = $this->tag_campaign_tag($customerjourney['lastVisit_campaign']);
                        if($customerjourneys['tag_source'] == $customerjourneys_tag_source){
                            $customerjourneys['tag_campaign'] = $tag_campaign;
                        }
                    }
                }
                if(!empty($customerjourney['last_campaign']) && $customerjourneys['tag_campaign'] == "LabelIsEmpty"){
                    $tag_campaign = $this->tag_campaign($customerjourney['last_campaign']);
                    if($tag_campaign !== "LabelIsEmpty"){
                        $customerjourneys_tag_source = $this->tag_campaign_tag($customerjourney['last_campaign']);
                        if($customerjourneys['tag_source'] == $customerjourneys_tag_source){
                            $customerjourneys['tag_campaign'] = $tag_campaign;
                        }
                    }
                }
                return $customerjourneys;
            }
        }

        //0614 临时规则
        //bra60- 张兴
        if(!empty($customerjourney['landing_site'])){
            $domain = stristr($customerjourney['landing_site'],"bra60-");
            if($domain){
                $customerjourneys['tag_source'] = "fb";
                $customerjourneys['tag_campaign'] = "zx";
                return $customerjourneys;
            }
        }
        //直接访问
        if($customerjourney['first_source'] == "direct" || $customerjourney['first_campaign'] == "www.google.com/organic"){
            $customerjourneys['tag_source'] = "直接访问";
            $customerjourneys['tag_campaign'] = "LabelIsEmpty";
            return $customerjourneys;
        }
        
        if($customerjourney['last_campaign'] == "linktr.ee/referral" || $customerjourney['last_source'] == "linktr.ee"){
            $customerjourneys['tag_source'] = "fb";
            $customerjourneys['tag_campaign'] = "LabelIsEmpty";
            return $customerjourneys;
        }
        if($customerjourney['last_campaign'] == "--/ads"){
            $customerjourneys['tag_source'] = "tt";
            $customerjourneys['tag_campaign'] = "LabelIsEmpty";
            return $customerjourneys;
        }
        if(!empty($customerjourney['first_campaign']) && !empty($customerjourney['last_campaign'])){
            $tag_campaign = $this->tag_campaign($customerjourney['first_campaign']);
            if($tag_campaign !== "LabelIsEmpty"){
                $customerjourneys['tag_source'] = $this->tag_campaign_tag($customerjourney['first_campaign']);
                $customerjourneys['tag_campaign'] = $tag_campaign;
                return $customerjourneys;
            }
            $tag_campaign = $this->tag_campaign($customerjourney['last_campaign']);
            if($tag_campaign !== "LabelIsEmpty"){
                $customerjourneys['tag_source'] = $this->tag_campaign_tag($customerjourney['last_campaign']);
                $customerjourneys['tag_campaign'] = $tag_campaign;
                return $customerjourneys;
            }
        }
        return $customerjourneys;
    }

    /**
    * 判断来源
    * @param array params
    */
    public function tag_campaign($source)
    {
        $str3 = $this->config('str3');
        $msg = "LabelIsEmpty";
        foreach ($str3 as $k=>$v) {
            $domain = stristr($source,$v);
            if($domain){
                if($v == "bra60"){
                    $msg = "zx";
                }elseif($v == "fei"){
                    $msg = "lxf";
                }else{
                    $msg = $v;
                }
                break;
            }
        }
        return $msg;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function tag_campaign_tag($source)
    {
        $str3 = $this->config('str3');
        $str7 = $this->config('str7');
        $msg = "LabelIsEmpty";
        if(!empty($source)){
            foreach ($str3 as $k=>$v) {
                $domain = stristr($source,$v);
                if($domain){
                    $msg = $str7[$k];
                    break;
                }
            }
        }
        return $msg;
    }

    /**
    * 方法详情
    * @param array params
    */
    public function tag_landing_site($source)
    {
        $str3 = $this->config('str3');
        $msg = "LabelIsEmpty";
        if(!empty($source)){
            foreach ($str3 as $k=>$v) {
                $domain = stristr($source,"=".$v);
                if($domain){
                    $msg = $str3[$k];
                    break;
                }
            }
        }
        return $msg;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function tag_site($source)
    {
        $str10 = $this->config('str10');
        $str11 = $this->config('str11');
        $msg = "LabelIsEmpty";
        if(!empty($source)){
            foreach ($str10 as $k=>$v) {
                $domain = stristr($source,$v);
                if($domain){
                    $msg = $str11[$k];
                    break;
                }
            }
        }
        return $msg;
    }
    /**
    * 方法详情
    * @param array params
    */
    public function config($key)
    {
        $data['str1'] = [
            "Facebook",
            "Instagram",
            "TikTok",
            "ad_google",
        ];
        $data['str3'] = [
            "lxf",
            "rjw",
            "txl",
            "mf",
            "bwh",
            "zby",
            "gjw",
            "zjl",
            "wd",
            "ry",
            "wyl",
            "lxy",
            "dqh",
            "ljx",
            "gjl",
            "zsw",
            "xjw",
            "zcc",
            "wb",
            "lh",
            "ld",
            "mml",
            "hgx",
            "lh",
            "dl",
        ];
        $data['str7'] = [
            "fb",
            "fb",
            "fb",
            "ggad",
            "fb",
            "ggad",
            "fb",
            "fb",
            "ggad",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
            "ggad",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
            "fb",
        ];
        $data['str10'] = [
            "fbclid",
            "gclid",
            "ttclid",
        ];
        $data['str11'] = [
            "fb",
            "ggad",
            "tt",
        ];
        if(!empty($key)){
            return $data[$key];
        }
        return $data;
    }

    /**
    * 客户行为日志
    * @param array params
    */
    public function CustomerBehaviorLog()
    {
        // $count = Db::name('order_source')
        //     ->where('graphql_status',0)
        //     ->where('order_id',"<>","")
        //     ->where('createtime',">=",1727712000)
        //     ->where('createtime',"<=",1730390400)
        //     ->count();
        //     halt($count);
            
        $order = Db::name('order_source')
            ->where('graphql_status',0)
            ->where('order_id',"<>","")
            ->where('createtime',">=",1727712000)
            ->where('createtime',"<=",1730390400)
            ->order('createtime desc')
            ->find();
        if(empty($order)){
            return success('暂无数据');
        }
        $shop_info = Db::name('shops')
            ->where('id', $order['shop_id'])
            ->find();
        $this->customer($order['order_id'],$shop_info['app_secret'],$shop_info['myshopify_domain']);
        return success('完成');
    }

    /**
    * @desc    查找metafields
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SearchForMetafields($params)
    {
        $order_id        = $params['order_id'] ?? 0;
        if (!empty($order_id)) {
            $where[]  = ['a.order_id', '=', $order_id];
        }else{
            $where[]  = ['a.dispute_time', '=', 0];
        }

        $shop_info = Db::name('order')
            ->field('
                a.id,
                a.order_id,
                a.shop_id,
                b.myshopify_domain,
                b.app_key,
                b.app_secret
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->where($where)
            ->order('id desc')
            ->find();
        if(empty($shop_info)){
            return  $this->jsonMessage(201,false,'暂无数据',null);
        }
        
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$shop_info['order_id']."/metafields.json";   
        $return = HttpUtil::getUrl($url, $shop_info);
        if(!empty($return)){
            $return = json_encode($return, true);
            $update = [];
            $update['dispute_json'] = $return;
            $update['dispute_time'] = time();
            Db::name('order')
                ->where('order_id',$shop_info['order_id'])
                ->update($update);
        }
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 获取Shopline订单列表
     * @author zhangheng
     */
    public function ApiOrderListShopline($params = [])
    {
        $type           = $params['type'] ?? '2'; //1更新 2获取历史记录
        $shop_id        = $params['shop_id'] ?? 20;
        
        if(empty($shop_id)){
            return json(DefaultResponse(201, false, '暂无店铺!', null));
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopline.api_versoin');
        $operation      = Config('Logisticskey.shopline.orders_path');
        $url            = $shop_info['myshopify_domain'].$version . $operation;
        
        switch ($type) {
            case '1':
                $limit = 50;
                
                $last_order = Db::name('order')
                    ->where('shop_id', $shop_info['id'])
                    ->order(['updated_at' => 'desc'])
                    ->find();
                if (!empty($last_order['updated_at'])) {
                    $updated_at_min = $last_order['updated_at'];
                } else {
                    date_default_timezone_set('Asia/Shanghai');
                    $updated_at_min = '2023-07-01T00:00:00-07:00';
                }
                $url = $url . '?updated_at_min=' . $updated_at_min . '&limit=' . $limit . '&status=any';
                
                break;
            case '2':
                $limit = 10;
                    if (!empty($shop_info['ControlUpdateTime'])) {
                        $created_at_max = $shop_info['ControlUpdateTime'];
                    } else {
                        date_default_timezone_set('Asia/Shanghai');
                        $created_at_max = '2024-05-01T00:00:00-07:00';
                    }
                $url = $url . '?created_at_min=' . $created_at_max . '&limit=' . $limit . '&status=any';
                break;
            default:
        }
        $return = HttpUtil::getUrlshopline($url, $shop_info);
        // halt($return);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }
        if(!empty($return)){
            Db::startTrans();
            try {
                //存入数据
                $this->ProcessOrders($return,$shop_info['id'],$type);
                
                Db::commit();
                return json(DefaultResponse(200, true, '操作成功', ''));
            } catch (ValidateException $e) {
                Db::rollback();
                return json(DefaultResponse(200, true, $e->getError(), ''));
            } catch (\Exception $e) {
                Db::rollback();
                return json(DefaultResponse(200, true, $e->getMessage(), ''));
            }
        }else{
            return json(DefaultResponse(200, true, '暂无数据', ''));
        }
    }

    /**
    * @desc    添加metafields
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function AddMetafields($params)
    {
        $order_id        = $params['order_id'] ?? 0;
        $shop_info = Db::name('order_achievement')
            ->field('
                a.id,
                a.order_id,
                a.shop_id,
                a.disputeapi_type,
                a.disputeapi_status,
                b.myshopify_domain,
                b.app_key,
                b.app_secret
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            // ->where('order_id',$order_id)
            ->where('disputeapi_type',"<>",'')
            ->where('disputeapi_status',"<>",'其他')
            ->where('metafields_status',"=",0)
            ->find();
            // halt($shop_info);
        if (empty($shop_info)) {
            return json(DefaultResponse(201, false, "该订单暂无争议信息", null));
        }
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$shop_info['order_id']."/metafields.json";   

        $post = array();
        $post['metafield']['namespace'] = 'custom';
        $post['metafield']['key'] =  '_dispute';
        $post['metafield']['value'] = [
            '0' => $shop_info['disputeapi_status'],
        ];
        $post['metafield']['value'] = json_encode($post['metafield']['value'], true);
        $post['metafield']['type'] = 'list.single_line_text_field';
        // halt($post);
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        $return = json_decode($return, true);
        if(!empty($return['errors']) || !empty($return['error'])){
            $update['metafields_status'] = 2;
            Db::name('order_achievement')
                ->where('id',$shop_info['id'])
                ->update($update);
            return json(DefaultResponse(200, true, '添加失败', $return));
        }else{
            $update['metafields_status'] = 1;
            Db::name('order_achievement')
                ->where('id',$shop_info['id'])
                ->update($update);

            return json(DefaultResponse(200, true, '添加成功', ''));
        }
    }

     /**
    * @desc    添加metafields
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function AddMetafieldsAfterpay($params)
    {
        $order_id        = $params['order_id'] ?? 0;
        $shop_info = Db::name('order_dispute_afterpay')
            ->field('
                a.id,
                a.order_id,
                a.shop_id,
                order,
                a.uploadstatus,
                b.myshopify_domain,
                b.app_key,
                b.app_secret
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->where('shop_id',"=",17)
            ->where('order_id',">",0)
            ->where('uploadstatus',"=",0)
            ->find();
            // halt($shop_info);
        if (empty($shop_info)) {
            return json(DefaultResponse(201, false, "该订单暂无争议信息", null));
        }
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$shop_info['order_id']."/metafields.json";   

        $post = array();
        $post['metafield']['namespace'] = 'custom';
        $post['metafield']['key'] =  'afterpay';
        $post['metafield']['value'] = [
            '0' => $shop_info['order'],
        ];
        $post['metafield']['value'] = json_encode($post['metafield']['value'], true);
        $post['metafield']['type'] = 'single_line_text_field';
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        $return = json_decode($return, true);
        if(!empty($return['errors']) || !empty($return['error'])){
            $update['uploadstatus'] = 2;
            Db::name('order_dispute_afterpay')
                ->where('id',$shop_info['id'])
                ->update($update);
            return json(DefaultResponse(200, true, '添加失败', $return));
        }else{
            $update['uploadstatus'] = 1;
            Db::name('order_dispute_afterpay')
                ->where('id',$shop_info['id'])
                ->update($update);

            return json(DefaultResponse(200, true, '添加成功', $return));
        }
    }

    /**
    * @desc    实时汇率查询
    * @date    2024/8/27
    * @author  zhangheng
    * @url  https://shopify.haiyu2.fun/api/ApiOrder/RealTimeExchangeRateInquiry?type=1
    */
    public function RealTimeExchangeRateInquiry($params)
    {
        //类型 1欧元转美金
        $type = $params['type'] ?? 1;
        switch ($type) {
            case '1':
                $ExchangeRateFront = "eur";
                $ExchangeRateAfter = "usd";
                break;
            default:
                $ExchangeRateFront = "eur";
                $ExchangeRateAfter = "usd";
        }
        $date = date('Y-m-d', time() - timezone());

        $euroToUsdRate = Cache::store('redis')->get('euroToUsdRate'.$date);
        if (empty($euroToUsdRate)) {  
            $url = "https://chl.cn/huilv/huansuan-ajax.asp?1*".$ExchangeRateFront."*".$ExchangeRateAfter."*".$date;
            $return = HttpUtil::getUrlEx($url);
            //匹配
            $euroToUsdRate = 0;
            if(!empty($return)){
                // if (preg_match('/<em>(.*?)<\/em>/', $return, $matches)) {
                if (preg_match_all('/<em>(.*?)<\/em>/s', $return, $matches)) {  
                    if(isset($matches[1][1]) && !empty($matches[1][1])){
                        $euroToUsdRate = $matches[1][1];  
                    }
                }
            }
            Cache::store('redis')->set('euroToUsdRate'.$date, $euroToUsdRate, 3600 * 24); // 缓存24小时  
        } 
        return $euroToUsdRate;
    }

    

    /**
    * @desc    注册17track
    * @date    2024/10/27
    * @author  zhangheng
    */
    public function sync_track_register_718($order_number)
    {
        $data = array();
        $data['trackNum'] = $order_number;
        $data2[] = $data;
        $url = "https://apigetway.track718.net/v2/tracks";
        $return = HttpUtil::trackPostUrl718($url, $data2);
        // halt($return);
        return true;
    }


    /**
    * @desc    注册17track
    * @date    2024/10/27
    * @author  zhangheng
    */
    public function sync_track_info_718($order_number)
    {
        $data = array();
        $data['trackNum'] = $order_number;
        $data2[] = $data;
        $url = "https://apigetway.track718.net/v2/tracking/query";
        $return = HttpUtil::trackPostUrl718($url, $data2);
        // halt($return);
        return $return;
    }

    /**
    * @desc    注册17track
    * @date    2024/10/27
    * @author  zhangheng
    */
    public function sync_track_register($order_number)
    {
        $data = array();
        $data['number'] = $order_number;
        $data2[] = $data;
        $url = "https://api.17track.net/track/v2.2/register";
        HttpUtil::trackPostUrl($url, $data2);
        return true;
    }
    /**
    * @desc    17track
    * @date    2024/10/27
    * @author  zhangheng
    */
    public function webhooksTrack($post)
    {
        //没钱先屏蔽
        return true;
        
        htmlLog(['params'=>$post],OPERATE_LOG . date('Ym') . '/webhooksTrack/' . date('Ymd') . '.txt');
        $track_number       = $post['data']['number']??'';
        $list               = $post['data']['track_info']??[];
        //接收地址;
        $recipient_address  = $list['shipping_info']['recipient_address']['country']??'US';
        //最新的物流主状态;
        $latest_status      =  $list['latest_status']['status']??'';
        //最新物流子状态;
        $latest_sub_status  =  $list['latest_status']['sub_status']??'';

        if($latest_status == 'Delivered_Other'){
            // return true;
        }

        //发送提供的物流商和国家;
        $tracking_provider_country = $list['tracking']['providers'][0]['provider']['country']??'US';
        $tracking_provider_name    = $list['tracking']['providers'][0]['provider']['name']??'';
        //tracking数组;
        $tracking_info             = [];
        $tracking_list             = $list['tracking']['providers'][0]['events']??'';
        if($tracking_list){
            foreach($tracking_list as $v){
                $temp['time_raw']    = updatetime_automatic_date($v['time_iso']);
                $temp['location']    = $v['location'];
                $temp['description'] = $v['description'];
                $temp['sub_status']  = $v['sub_status'];
                $tracking_info[]     = $temp;
            }
        }

        $insert_data =  [
            'track_number'     =>$track_number,
            'provider_country' =>$recipient_address,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$tracking_provider_country,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
            'create_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $update_data = [
            'track_number'     =>$track_number,
            'provider_country' =>$recipient_address,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$tracking_provider_country,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $exist_info = Db::name('order_track')->field('id,order_id,latest_status,shop_id,track_number')->where(['track_number'=>$track_number])->find();
        if(empty($exist_info)){
            $order_info = Db::name('order')->field('id,order_id,shop_id')->where(['tracking_number'=>$track_number])->find();
            $insert_data['order_id'] = $order_info['order_id']??'';
            $insert_data['shop_id']  = $order_info['shop_id']??'';
            Db::name('order_track')->insert($insert_data);
            //修改配送状态
            $this->updateOrderLogisticsStatus($insert_data);
        }else{
            Db::name('order_track')->where(['id'=>$exist_info['id']])->update($update_data);
            //修改配送状态
            $this->updateOrderLogisticsStatus($update_data,$exist_info);
        }

        //更新订单表物流在途状态
        Db::name('order')
            ->where('tracking_number', $track_number)
            ->update(['LogisticsStatus' => $latest_status]);

        Db::name('order_achievement')
            ->where('tracking_number', $track_number)
            ->update(['LogisticsStatus' => $latest_status]);

        return true;
    }

    
    /**
    * @desc    17track
    * @date    2025/07/15
    * @author  zhangheng
    */
    public function webhooksTrack718($post)
    {
        htmlLog(['params'=>$post],OPERATE_LOG . date('Ym') . '/webhooksTrack718/' . date('Ymd') . '.txt');
        $track_number       = $post['list'][0]['track_num']??'';

        //log
        $log_data = [
            'track_number'      =>$track_number,
            'json'              =>json_encode($post),
            'timestamp'              =>time(),
        ];
        Db::name('webhooks718')->insert($log_data);
        //log

        $list               = $post['list'][0]['fromDetail']??[];
        //接收地址;
        $recipient_address  = $post['list'][0]['country']??'US';
        $status_sub_arr     = Config('Logisticskey.718_info.sub_status_key');
        $status_arr         = Config('Logisticskey.718_info.status_key');
        $status_17_staus    = Config('Logisticskey.718_info.718_17_status');
        //最新的物流主状态;
        $subResult          =  $post['list'][0]['latest']['subResult']??'';
        $result             =  $post['list'][0]['latest']['result']??'';
        $latest_status      =  $status_arr[$result]??'';
        $latest_status      =  $status_17_staus[$latest_status]??'';
        //最新物流子状态;
        $latest_sub_status  =  $status_sub_arr[$subResult]??'';

        if($latest_status == 'Delivered'){
            // return true;
        }

        //发送提供的物流商和国家;
        $tracking_provider_country = $post['list'][0]['originCountry']??'CN';
        $tracking_provider_name    = '';

        //tracking数组;
        $tracking_info             = [];
        $tracking_list             = $list;

        if($tracking_list){
            foreach($tracking_list as $v){
                $temp['time_raw']    = $v['date'];
                $temp['location']    = '';
                $temp['description'] = $v['status'];
                $temp['sub_status']  = $status_sub_arr[$v['subResult']]??'';
                $tracking_info[]     = $temp;
            }
        }

        $insert_data =  [
            'track_number'     =>$track_number,
            'provider_country' =>$tracking_provider_country,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$recipient_address,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'platform_track'   =>1,
            'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
            'create_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $update_data = [
            'track_number'     =>$track_number,
            'provider_country' =>$tracking_provider_country,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$recipient_address,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'platform_track'   =>1,
            'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $exist_info = Db::name('order_track')->field('id,order_id,latest_status,shop_id,track_number')->where(['track_number'=>$track_number])->find();
        if(empty($exist_info)){
            $order_info = Db::name('order')->field('id,order_id,shop_id')->where(['tracking_number'=>$track_number])->find();
            $insert_data['order_id'] = $order_info['order_id']??'';
            $insert_data['shop_id']  = $order_info['shop_id']??'';
            Db::name('order_track')->insert($insert_data);
            //修改配送状态--先关闭
            $this->updateOrderLogisticsStatus($insert_data);
        }else{
            Db::name('order_track')->where(['id'=>$exist_info['id']])->update($update_data);
            //修改配送状态--先关闭
            $this->updateOrderLogisticsStatus($insert_data);
        }

        //更新订单表物流在途状态
        Db::name('order')
            ->where('tracking_number', $track_number)
            ->update(['LogisticsStatus' => $latest_status]);

        Db::name('order_achievement')
            ->where('tracking_number', $track_number)
            ->update(['LogisticsStatus' => $latest_status]);

        return true;
    }

    /**
    * @desc    修改配送状态
    * @date    2025/6/16
    * @author  zhangheng
    */
    public function updateOrderLogisticsStatus($data,$exist_info = [])
    {
        if(empty($data['latest_status'])){
            return true;
        }
        $latest_status = '';
        if(empty($exist_info)){
            $latest_status = $data['latest_status'];
        }else{
            if($data['latest_status'] !== $exist_info['latest_status']){
                $latest_status = $data['latest_status'];
            }
        }
        // halt($latest_status);
        
        switch ($latest_status) {
            case 'Delivered':
                $status = 'delivered';
                break;
            case '签收':
                $status = 'delivered';
                break;
            case '转运中':
                $status = 'in_transit';
                break;
            case 'InTransit':
                $status = 'in_transit';
                break;
            case 'InfoReceived':
                $status = 'confirmed';
                break;
            // case '收货':
            //     $status = 'delivered';
            //     break;
            case 'OutForDelivery':
                $status = 'out_for_delivery';
                break;
            case 'DeliveryFailure':
                $status = 'failure';
                break;
            case '投递失败':
                $status = 'failure';
                break;
            case 'AvailableForPickup':
                $status = 'ready_for_pickup';
                break;
            case '退仓':
                $status = 'failure';
                break;
            default:
                $status = '';
        }
        $order = Db::name('order_achievement')->where('tracking_number',$data['track_number'])->find();

        //日志
        $log = [
            'shipment_status' => $order['shipment_status'] ?? "",
            'order_id' => $order['order_id'] ?? 0,
            'shop_id' => $order['shop_id'] ?? 0,
            'shopify_status' => $status ?? "",
            'track_number' => $data['track_number'] ?? "",
            'latest_status' => $latest_status ?? "",
            'update_time'   => date("Y-m-d H:i:s", time()),
        ];
        //日志
        // halt($log);
        //开始修改配送状态
        $msg = '';
        $order_id = $log['order_id'];
        $shop_id = $log['shop_id'];
        $status = $log['shopify_status'];
        
        $shipment_status = $order['shipment_status'] ?? "";

        if(empty($order)){
            // $msg = '没有找到该订单';
            // //日志
            // $log['msg'] = $msg;
            // Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }

        // 从4月开始
        $createtime = $order['createtime'] ?? 0;
        if($createtime < time() - 86400 * 30*4){
            return true;
        }
        // 只要4px和dyy开头的
        if(strpos($data['track_number'], '4PX') === false && strpos($data['track_number'], 'DYY') === false){
            return true;
        }
        

        if(empty($status)){
            $msg = '状态不匹配,原状态'.$latest_status;
            //日志
            $log['msg'] = $msg;
            Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }
        
        
        if($shipment_status == $status){
            $msg = '状态没变化不更新';
            //日志
            $log['msg'] = $msg;
            Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }
        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments.json";
        // halt($log);
        $fulfillments = HttpUtil::getUrl($url, $shop_info);
        // halt($fulfillments);
        $fulfillment_id = $fulfillments['fulfillments'][0]['id'] ?? 0;
        if($fulfillment_id == 0){
            $msg = '没有可发货的订单';
            //日志
            $log['msg'] = $msg;
            Db::name('order_tracklog')->insert($log);
            //日志
            return true;
        }
        //物流详情
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments/".$fulfillment_id."/events.json";
        //新增
        $data_fulfillment = [];
        $data_fulfillment['status'] = $status;
        $data_fulfillments = [
            'event' => $data_fulfillment
        ];
        $return = HttpUtil::PostUrl($url,$data_fulfillments, $shop_info);
        $msg = $return;

        //日志
        $log['msg'] = $msg;
        Db::name('order_tracklog')->insert($log);
        //日志
        return true;
    }

    /**
    * @desc    客户订阅
    * @date    2024/10/27
    * @author  zhangheng
    */
    public function customersSubscribe($params = [])
    {
        // $update['accepts_marketing'] = "";
        // $count = Db::name('order_customer')
        //     ->where('accepts_marketing',"自动订阅成功")
        //     ->update($update);
        // halt($count);
        $type = $params['type'] ?? 1;
        $where = [];
        switch ($type) {
            case '1':
                $where[] = ['created_at', '>', "2024-11-01"];
                break;
            case '2':
                $where[] = ['created_at', '>', "2024-10-01"];
                $where[] = ['created_at', '<', "2024-11-01"];
                break;
            case '3':
                $where[] = ['created_at', '>', "2024-09-01"];
                $where[] = ['created_at', '<', "2024-10-01"];
            case '4':
                $where[] = ['created_at', '>', "2024-08-01"];
                $where[] = ['created_at', '<', "2024-09-01"];
            default:
        }
        
        $shop_id = $params['shop_id'] ?? 17;
        $customer = Db::name('order_customer')
            ->where('shop_id',$shop_id)
            ->where('accepts_marketing',"")
            ->where($where)
            ->order("created_at desc")
            ->find();
        if(empty($customer)){
            return json(DefaultResponse(201, false, "完成", null)); 
        }
        $shop_info['myshopify_domain'] = 'https://vfaja.myshopify.com';
        $shop_info['app_key'] = '8482dba02c86867ac54b8022e7f0e9f7';
        $shop_info['app_secret'] = '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';

        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/customers/".$customer['customer_id'].".json";
        $return = HttpUtil::getUrl($url, $shop_info);
        // halt($return);
        $customer_tags = $customers['tags'] ?? ""; //原始标签
        $new_tags = "sms20241118";
        if(!empty($customer_tags)){
            //如果customer_tags不包含sms20241118则添加
            if(strpos($customer_tags, $new_tags) === false){
                $tags_new = $customer_tags . "," . $new_tags;
            }else{
                $tags_new = $customer_tags; 
            }
        }else{
            $tags_new = $new_tags;
        }
        $tags_new = array_unique(explode(",", $tags_new));
        $post['customer']['id'] = $customer['customer_id'];
        $post['customer']['tags'] = $tags_new;

        $post['customer']['phone'] = $return['customer']['phone'] ?? "";
        if(empty($post['customer']['phone'])){
            $post['customer']['phone'] = $return['customer']['addresses'][0]['phone'] ?? "";
        }
        // 客户订阅
        $post['customer']['id'] = $customer['customer_id'];
        $post['customer']['accepts_marketing'] = true;
        $post['customer']['accepts_marketing_updated_at'] = '2024-11-17T15:32:56-04:00';
        
        $post['customer']['sms_marketing_consent']['state'] = 'subscribed';
        $post['customer']['sms_marketing_consent']['opt_in_level'] = $return['customer']['sms_marketing_consent']['opt_in_level'] ?? "single_opt_in";

        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/customers/".$customer['customer_id'].".json";
        $return = HttpUtil::puturl($url,$post,$shop_info);
        // halt($return);
        if (!empty($return['errors'])) {
            $update['accepts_marketing'] = "错误";
            Db::name('order_customer')
                ->where('customer_id',$customer['customer_id'])
                ->update($update);
            return json(DefaultResponse(201, false, json_encode($return['errors']), null));
        }else{
            $update['accepts_marketing'] = "自动订阅成功";
            $update['phone'] = $post['customer']['phone'];
            $update['tags'] = implode(",", $post['customer']['tags']);
            $return = Db::name('order_customer')
                ->where('customer_id',$customer['customer_id'])
                ->update($update);
            return json(DefaultResponse(200, false, "完成", $customer['customer_id'])); 
        }
    }


    /**
     * @desc   创建变体修改对象ID
     * @author xx
     * @date   2024-12-25
     */
    public function createCalculatedOrderId($params){
        $orderId        = $params['order_id']??'';
        $shop_id        = $params['shop_id'] ?? '';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.graphql_path');
        $url            = $shop_info['myshopify_domain'].$version.$operation;
        // 构建 GraphQL mutation
        $data = <<<QUERY
                mutation beginEdit {
                    orderEditBegin(id: "gid://shopify/Order/{$orderId}") {
                        calculatedOrder {
                            id
                        }
                    }
                }
QUERY;

        $result = HttpUtil::postUrlShopify($url,['query' => $data],$token);
        $CalculatedOrder     = $result['data']['orderEditBegin']['calculatedOrder']['id']??'';
        htmlLog(['response'=>$result],OPERATE_LOG . date('Ym') . '/createCalculatedOrderId/' . date('Ymd') . '.txt');
        if($CalculatedOrder){
            $parts = explode("/", $CalculatedOrder);  // 将字符串按斜杠分割为数组
            $CalculatedOrderId = end($parts);
        }else{
            $CalculatedOrderId = '';
        }

        Db::name('order_varient_log')->where(['order_id'=>$orderId])->update(
            [
                'order_id'            => $orderId,
                'calculated_order_id' => $CalculatedOrderId,
                'create_time'         => date("Y-m-d H:i:s", time()),
            ]
        );
        return $CalculatedOrderId;
    }


    public function change_info(){
        $t1           = microtime(true);
        $where        = [];
        $where[]      = ['latest_status','<>','Delivered'];
        $count        = Db::name('order_track')->where($where)->field('id,order_id,shop_id')->count();
        $executedCount= 0;
        $pageSize     = 10;
        $page         = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $list   = Db::name('order_track')
                ->where($where)
                ->field('id,order_id,shop_id,tracking_list')
                ->limit(($i - 1) * $pageSize, $pageSize)
                ->select();
            $list   = objectToArray($list);
            $arr    = [];
            foreach($list as $v){
                if(!$v['tracking_list']){
                       Db::name('order_track')->where(['id'=>$v['id']])->update([
                           'type' =>1
                       ]);
                }

                if($v['tracking_list']){
                    $tracking_list = json_decode($v['tracking_list'],true);
                    if(is_array($tracking_list)){
                        $current = current($tracking_list);
                        $time    = $current['time_raw'];
                        if($time && (time()-strtotime($time)>2592000)){
                            Db::name('order_track')->where(['id'=>$v['id']])->update([
                                'type'        =>1,
                                'latest_time' =>$time,
                            ]);
                        }
                    }
                }
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
            Db::name('order_track')->insertAll($arr);
            echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
        }

        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }






    /**
     * @desc   获取lineItemId
     * @author xx
     * @date   2024-12-25
     */
    public function get_varient_id($params){
        $orderId        = $params['order_id']??'';
        $shop_id        = $params['shop_id'] ?? '';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'] . $version . '/orders/' . $orderId . '.json';
        $result         = HttpUtil::getUrlShopify($url,$token);
        $order_info     = $result['order']['line_items'][1]['variant_id']??[];
        htmlLog(['response'=>$result],OPERATE_LOG . date('Ym') . '/get_varient_id/' . date('Ymd') . '.txt');
        $variant_id = '';
        if($order_info){
            $parts = explode("/", $order_info);  // 将字符串按斜杠分割为数组
            $variant_id = end($parts);
        }
        return $variant_id;
    }





    /**
     * @desc   获取lineItemId
     * @author xx
     * @date   2024-12-25
     */
    public function get_lineItemId($params){
        $orderId        = $params['order_id']??'';
        $shop_id        = $params['shop_id'] ?? '';
        $new_varient_id = $params['new_varient_id'] ??'';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'] . $version . '/orders/' . $orderId . '.json';
        $result         = HttpUtil::getUrlShopify($url,$token);
        $order_info     = $result['order']['line_items']??[];
        htmlLog(['response'=>$result],OPERATE_LOG . date('Ym') . '/get_lineItemId/' . date('Ymd') . '.txt');
        $lineItemId = '';
        if($order_info){
             //获取当前新变体ID;
             foreach($order_info as $v){
                    if($v['variant_id'] == $new_varient_id){
                        $lineItemId =$v['id']; continue;
                    }
             }
        }

        Db::name('order_varient_log')->where(['order_id'=>$orderId])->update(
            [
                'order_id'            => $orderId,
                'line_item_id'        => $lineItemId,
                'create_time'         => date("Y-m-d H:i:s", time()),
            ]
        );
        return $lineItemId;
    }


    /**
     * @desc   添加新变体
     * @author xx
     * @date   2024-12-25
     */
    public function addCalculatedOrder($params){
        $orderId        = $params['order_id']??'';
        $new_varient_id = $params['new_varient_id'] ??'';
        $shop_id        = $params['shop_id'] ?? '';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.graphql_path');
        $url            = $shop_info['myshopify_domain'].$version.$operation;
        $calculated_order_id = self::createCalculatedOrderId($params);
        // 构建 GraphQL mutation
        $data = <<<QUERY
                         mutation addVariantToOrder{
              orderEditAddVariant(id: "gid://shopify/CalculatedOrder/{$calculated_order_id}", variantId: "gid://shopify/ProductVariant/{$new_varient_id}", quantity: 1){
                calculatedOrder {
                  id
                  addedLineItems(first:5) {
                    edges {
                      node {
                        id
                        quantity
                      }
                    }
                  }
                }
                userErrors {
                  field
                  message
                }
              }
            }
QUERY;

        $result     = HttpUtil::postUrlShopify($url,['query' => $data],$token);
        $userErrors = $result['data']['orderEditAddVariant']['userErrors']??[];
        htmlLog(['response'=>$result],OPERATE_LOG . date('Ym') . '/addCalculatedOrder/' . date('Ymd') . '.txt');
        if($userErrors){
            Db::name('order_varient_log')->where(['order_id'=>$orderId])->update(
                [
                    'res_json'            => json_encode($userErrors),
                    'create_time'         => date("Y-m-d H:i:s", time()),
                ]
            );
        }
        //提交编辑接口;
        self::pushUpdateOrder(['calculated_order_id'=>$calculated_order_id,'shop_id'=>$shop_id]);
        //推动数据到队列;
        MqTaskPushLogic::mq_task_push(
            '',
            MqQueueName::QUEUE_ORDER_ADD_DISCOUNT_QUEUE,
            [
                'shop_id'       =>$shop_id,
                'order_id'      =>$orderId,
                'new_varient_id'=>$new_varient_id,
            ],
            false
        );
        return  true;
    }


    /**
     * @desc   添加折扣到变体
     * @author xx
     * @date   2024-12-25
     */
    public function addDiscountOrder($params){
        $shop_id        = $params['shop_id'] ?? '';
        $orderId        = $params['order_id'] ?? '';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.graphql_path');
        $url            = $shop_info['myshopify_domain'].$version.$operation;

        $new_createCalculatedOrderId = self::createCalculatedOrderId($params);
        $line_item_id                = self::get_lineItemId($params);
        // 构建 GraphQL mutation
        $data = <<<QUERY
 mutation addDiscount {
  orderEditAddLineItemDiscount(id: "gid://shopify/CalculatedOrder/{$new_createCalculatedOrderId}", lineItemId: "gid://shopify/CalculatedLineItem/{$line_item_id}", discount: {percentValue: 100, description: "Product offer at checkout"}) {
    calculatedOrder {
      id
      addedLineItems(first:5) {
        edges {
          node {
            id
            quantity
          }
        }
      }
    }
    userErrors {
      message
    }
  }
}
QUERY;

        $result = HttpUtil::postUrlShopify($url,['query' => $data],$token);
        Db::name('order_varient_log')->where(['order_id'=>$orderId])->update(
            [
                'calculated_order_id' => $new_createCalculatedOrderId,
                'status'              => 1,
                'create_time'         => date("Y-m-d H:i:s", time()),
            ]
        );
        htmlLog(['response'=>$result,'params'=>$data],OPERATE_LOG . date('Ym') . '/addDiscountOrder/' . date('Ymd') . '.txt');
        //提交编辑接口;
        self::pushUpdateOrder(['calculated_order_id'=>$new_createCalculatedOrderId,'shop_id'=>$shop_id]);
        return  true;
    }


    /**
     * @desc   提交数据变更
     * @author xx
     * @date   2024-12-25
     */
    public function pushUpdateOrder($params){
        $calculated_order_id = $params['calculated_order_id'] ??'';
        $shop_id        = $params['shop_id'] ?? '';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.api_versoin');
        $operation      = Config('Logisticskey.shopify.graphql_path');
        $url            = $shop_info['myshopify_domain'].$version.$operation;
        // 构建 GraphQL mutation
        $data = <<<QUERY
                        mutation commitEdit {
  orderEditCommit(id: "gid://shopify/CalculatedOrder/{$calculated_order_id}", notifyCustomer: false) {
    order {
      id
    }
    userErrors {
      field
      message
    }
  }
}
QUERY;

        $result = HttpUtil::postUrlShopify($url,['query' => $data],$token);
        htmlLog(['response'=>$result],OPERATE_LOG . date('Ym') . '/pushUpdateOrder/' . date('Ymd') . '.txt');
    }


    public function pushUpdateOrderProduce($params){
        //获取当天时间的数据
        $where                   = [];
        $where[]                 = ['status','=',0];
        $list                    = Db::name('order_varient_log')->field('order_id,shop_id,new_varient_id')->where($where)->select();
        $list                    = objectToArray($list);

        if(!$list)    return '暂无数据!';
        foreach($list as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_UPDATE_VARIENT_QUEUE,
                $v,
                false
            );
        }
        $num = count($list);
        return '预发货处理数据'.$num.'条';
    }



    /**
    * 导出客户
    * @param array params
    */
    public function export_customer($params = [])
    {
        $old_shop_id = 13;
        $new_shop_id = 41;
        $order_id = $params['order_id'] ?? 0;
        $customer_id = $params['customer_id'] ?? 0;
        $where[] = ['shop_id',"=",$old_shop_id];
        $where[] = ['BackupStatus',"=",0];//迁移状态
        if(empty($customer_id)){
            $order_customer = Db::name('order_customer')->field('id,order_id,customer_id')->where($where)->order('id desc')->find();
            $order_id = $order_customer['order_id'];
            $customer_id = $order_customer['customer_id'];
        }
        if(empty($customer_id)){
            return json(DefaultResponse(201, false, "完成", null)); 
        }
        $shop_info = Db::name('shops')->where('id', $old_shop_id)->find();
        $shop_info_new = Db::name('shops')->where('id', $new_shop_id)->find();
        //订单customers
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/customers/".$customer_id.".json";
        $return = HttpUtil::getUrl($url,$shop_info);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, "查询客户".json_encode($return['errors']), null));
        }
        //先新增客户
        unset($return['customer']['id']);
        foreach ($return['customer']['addresses'] as $k=>$v) {
            unset($return['customer']['addresses'][$k]['id']);
            unset($return['customer']['addresses'][$k]['customer_id']);
        }
        // halt($return);
        $url = $shop_info_new['myshopify_domain'] . "/admin/api/2023-07/customers.json";
        $return = HttpUtil::PostUrl($url,$return, $shop_info_new);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, "新增客户".json_encode($return['errors']), null));
        }
        $customer_id = $return['customer']['id'];
        //创建客户成功
        
        //新增订单
        // $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id.".json";
        // $return = HttpUtil::getUrl($url,$shop_info);
        // if (!empty($return['errors'])) {
        //     return json(DefaultResponse(201, false, "查询订单".json_encode($return['errors']), null));
        // }
        // $url = $shop_info_new['myshopify_domain'] . "/admin/api/2023-07/orders.json";
        // unset($return['order']['id']);
        // $returnnew = [];
        // $returnnew['order']['line_items'] = $return['order']['line_items'];
        // $returnnew['order']['customer'] = $customer_id;
        // $returnnew['order']['customer']['financial_status'] = $return['order']['financial_status'];
        // $return = HttpUtil::PostUrl($url,$returnnew, $shop_info_new);
        // if (!empty($return['errors'])) {
        //     return json(DefaultResponse(201, false, "新增".json_encode($return['errors']), null));
        // }
        $update['BackupStatus'] = 1;
        Db::name('order_customer')->where('id',$order_customer['id'])->update($update);
        
        return json(DefaultResponse(200, false, "完成", $return));
    }

    /**
    * @desc    添加metafields
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function AddMetafields_customer($params)
    {
        $order_id        = $params['order_id'] ?? 0;
        $shop_info = Db::name('order_achievement')
            ->field('
                a.id,
                a.order_id,
                a.shop_id,
                a.disputeapi_type,
                a.disputeapi_status,
                b.myshopify_domain,
                b.app_key,
                b.app_secret
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            // ->where('order_id',$order_id)
            ->where('disputeapi_type',"<>",'')
            ->where('disputeapi_status',"<>",'其他')
            ->where('metafields_status',"=",0)
            ->find();
            // halt($shop_info);
        if (empty($shop_info)) {
            return json(DefaultResponse(201, false, "该订单暂无争议信息", null));
        }
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-10/orders/".$shop_info['order_id']."/metafields.json";   

        $post = array();
        $post['metafield']['namespace'] = 'custom';
        $post['metafield']['key'] =  '_dispute';
        $post['metafield']['value'] = [
            '0' => $shop_info['disputeapi_status'],
        ];
        $post['metafield']['value'] = json_encode($post['metafield']['value'], true);
        $post['metafield']['type'] = 'list.single_line_text_field';
        // halt($post);
        $return = HttpUtil::PostUrl($url,$post, $shop_info);
        $return = json_decode($return, true);
        if(!empty($return['errors']) || !empty($return['error'])){
            $update['metafields_status'] = 2;
            Db::name('order_achievement')
                ->where('id',$shop_info['id'])
                ->update($update);
            return json(DefaultResponse(200, true, '添加失败', $return));
        }else{
            $update['metafields_status'] = 1;
            Db::name('order_achievement')
                ->where('id',$shop_info['id'])
                ->update($update);

            return json(DefaultResponse(200, true, '添加成功', ''));
        }
    }

    /**
     * @desc    shopify创建退款
     * @date    2025/03/04
     * @author  zhangheng
     */
    public function ShopifyCreatesRefunds($params = [])
    {
        if (empty($params['order_id']) || empty($params['shop_id']) || empty($params['amount']) || empty($params['currency'])) {
            $return = [
                'msg' => '参数不完整',
                'data' => '',
                'code' => 201,
            ];
            return $return;
        }

        $order_id = $params['order_id'] ?? 0;
        $shop_id = $params['shop_id'] ?? 0;
        $amount = $params['amount'] ?? 0;
        $currency = $params['currency'] ?? "";

        // 获取店铺信息
        $shop_info = Db::name('shops')->where('id', $shop_id)->find();
        if (empty($shop_info)) {
            $return = [
                'msg' => '店铺信息不存在',
                'data' => '',
                'code' => 201,
            ];
            return $return;
        }

        try {
            // 构建请求URL
            $url = $shop_info['myshopify_domain'] . Config('Logisticskey.shopify.create_fullment_id') . $order_id . "/refunds.json";

            // 构建请求数据
            $data = [
                'refund' => [
                    'currency' => $currency,
                    'notify' => true,
                    'note' => "",
                    'transactions' => [
                        [
                            'amount' => $amount,
                            'gateway' => "cash",
                            'kind' => "refund",
                        ],
                    ],
                    'shipping' => [
                        'full_refund' => true,
                    ],
                ],
            ];
            // 发送POST请求
            $return = HttpUtil::PostUrl($url, $data, $shop_info);
            $returnData = json_decode($return, true);

            // 检查返回结果
            if (!empty($returnData['errors'])) {
                $return = [
                    'msg' => 'API返回错误',
                    'data' => $returnData['errors'],
                    'code' => 201,
                ];
                return $return;
            }
            // 异常处理
            $return = [
                'msg' => '退款创建成功',
                'data' => $returnData,
                'code' => 200,
            ];
            return $return;
        } catch (\Exception $e) {
            // 异常处理
            $return = [
                'msg' => '退款创建失败',
                'data' => $e->getMessage(),
                'code' => 201,
            ];
            return $return;
        }
    }

    /**
    * @desc    订单详情
    * @date    2025/03/06
    * @author  zhangheng
    */
    public function OrderDetails($params = [])
    {
        $order_id = $params['order_id'] ?? 0;
        if (empty($order_id)) {
            return json(DefaultResponse(201, false, '订单号错误!', null));
        }

        $row = Db::name('order_achievement')->where('order_id',$order_id)->find();
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }

        // 店铺信息
        $shops = Db::name('shops')->field('name')->where('id',$row['shop_id'])->find();
        // 客户信息
        $order_customer = Db::name('order_customer')->field('first_name,last_name')->where('order_id',$row['order_id'])->find();
        // 物流信息
        $order_fulfillments = Db::name('order_fulfillments')->field('created_at')->where('order_id',$row['order_id'])->order('created_at asc')->find();
        // 交易信息
        $order_transactions = Db::name('order_transactions')->field('created_at')->where('order_id',$row['order_id'])->order('created_at asc')->find();
        // 订单明细
        $order_info = Db::name('order_info')->field('product_id,sku,quantity,price,variant_title')->where('order_id',$row['order_id'])->select()->toArray() ?? [];

        $row = [
            'shop_name' => $shops['name'] ?? "",
            'order_id' => $row['order_id'] ?? 0,
            'order_name' => $row['name'] ?? "",
            'total_price' => $row['total_price'] ?? 0.0,
            'currency' => $row['currency'] ?? "",
            'createtime' => $row['createtime'] ? date("Y-m-d H:i:s", $row['createtime']) : "",
            'TimeOfPayment' => $order_transactions['created_at'] ? date("Y-m-d H:i:s", strtotime($order_transactions['created_at'])) : "",
            'OrderDeliveryTime' => $order_fulfillments['created_at'] ? date("Y-m-d H:i:s", strtotime($order_fulfillments['created_at'])) : "",
            'country_code' => $row['country_code'] ?? "",
            'order_customer' => ($order_customer['first_name'] ?? "") . " " . ($order_customer['last_name'] ?? ""),
            'tracking_number' => $row['tracking_number'] ?? "",
            'fulfillment_status' => $order_fulfillments['fulfillment_status'] ?? "",
            'order_info' => $order_info,
        ];
        return json(DefaultResponse(200, true, '获取成功', $row));
    }


    /**
    * @desc    订单sku详情
    * @date    2025/03/06
    * @author  zhangheng
    */
    public function OrderSkuDetails($params = [])
    {
        $order_id = $params['order_id'] ?? 0;
        if (empty($order_id)) {
            return json(DefaultResponse(201, false, '订单号错误!', null));
        }
        // 订单明细
        $order_info = Db::name('order_info')->field('sku,quantity')->where('order_id',$order_id)->select()->toArray() ?? [];
        foreach ($order_info as $k=>$v) {
            $pos = strpos($v['sku'], '-');
            if($pos !== false){
                $sku = explode('-',$v['sku']);
                //数量
                $km = count($sku) - 1;
                $numeric = is_numeric($sku[$km]) ? true : false;
                $Number = 1;
                if($numeric && $sku[$km] < 25){
                    //是数字并且小于100才计算数量
                    $Number = $sku[$km];
                }
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    foreach ($skuPlus as $key => $value) {
                        if (!isset($sku_map_new[$sku[0] . '-' . $value . '-' . $sku[2]])) {
                            $sku_map_new[$sku[0] . '-' . $value . '-' . $sku[2]] = 0;
                        }
                        $sku_map_new[$sku[0] . '-' . $value . '-' . $sku[2]] += (int)$Number*$v['quantity'];
                    }
                }else{
                    if (!isset($sku_map_new[$sku[0] . '-' . $sku[1] . '-' . $sku[2]])) {
                        $sku_map_new[$sku[0] . '-' . $sku[1] . '-' . $sku[2]] = 0;
                    }
                    $sku_map_new[$sku[0] . '-' . $sku[1] . '-' . $sku[2]] += (int)$Number*$v['quantity'];
                }
            }
        }
        $new_sku_strings = [];
        if(!empty($sku_map_new)){
            foreach ($sku_map_new as $k=>$v) {
                $new_sku_strings[] = [
                    'sku' => $k,
                    'quantity' => $v,
                ];
            }
        }
        return json(DefaultResponse(200, true, '获取成功', $new_sku_strings));
    }
    

        
    /**
    * @desc    测试交易
    * @author  zhangheng
    */
    public function TestTransaction()
    {
        //测试交易
        $json = Db::name('order_webhooks')->field('json')->where('order_id','6836130611570')->order('timestamp desc')->find();
        $order = json_decode($json['json'],true);
        $test = $this->order_refunds_handle($order,$order['shop_id']);
        halt($test);
    }

    /**
    * @desc    测试交易
    * @author  zhangheng
    */
    public function TestDeliveryStatus()
    {
        $track_number = 'SF6045312738253';
        $exist_info = Db::name('order_track')->field('id,order_id,latest_status,shop_id,track_number')->where(['track_number'=>$track_number])->find();
        $this->updateOrderLogisticsStatus($exist_info,$exist_info);
        echo "成功";
    }

    /**
    * 客服部拉取退款订单--查退款金额
    * @param array params
    */
    public function export_test2()
    {
        $where = [];
        $where[] = ['a.createtime', '>=', 1735660800];
        $where[] = ['a.createtime', '<=', time()];
        $where[]  = ['a.financial_status', 'in', ["refunded", "partially_refunded"]];
        // $where[]  = ['a.refund', '<=', 0];
        // $where[]  = ['a.order_id', '=', 6788809621874];
        $lists = Db::name('order_achievement')
            ->field('
            a.shop_id,a.name,a.order_id,a.financial_status,a.refund,a.old_total_price
            ')
            ->alias('a')
            ->where($where)
            ->select()
            ->toarray();
        $count = count($lists);
        $executedCount = 0;
        $executedCountsu = 0;
        $currency = "";
        foreach ($lists as $k=>$v) {
            // halt($v);
            
            if($v['financial_status'] == "refunded"){
                $refund_amount = $v['old_total_price'] ?? 0;
            }else{
                $refund_amount = Db::name('order_transactions')
                    ->field('Sum(amount) as refund_amount,currency')
                    ->where('order_id',$v['order_id'])
                    ->where('status',"success")
                    ->where('kind',"refund")
                    ->group('transactions_id')
                    ->select()->toarray();
                $currency = $refund_amount[0]['currency'] ?? "";
                $refund_amount = $refund_amount[0]['refund_amount'] ?? 0;
                // MXN
                switch ($currency) {
                    case 'USD':
                        $refund_amount = $refund_amount;
                        break;
                    case 'MXN':
                        $refund_amount = $refund_amount * 0.0536;
                        break;
                    case 'CAD':
                        $refund_amount = $refund_amount * 0.7364;
                        break;
                    case 'GBP':
                        $refund_amount = $refund_amount * 1.3654;
                        break;
                    case 'EUR':
                        $refund_amount = $refund_amount * 1.1767;
                        break;
                    case 'AUD':
                        $refund_amount = $refund_amount * 0.657;
                        break;
                    default:
                        $refund_amount = 0;
                }
                
                
            }
            //更新
            // halt($refund_amount);
            
            // if($refund_amount > 0){
                $executedCountsu++;
                Db::name('order_achievement')
                    ->where('order_id',$v['order_id'])
                    ->update([
                        'refund' => $refund_amount,
                    ]);
            // }
            $executedCount++;
            echo "总数：".$count.",当前".$executedCount.",币种".$currency.",成功".$executedCountsu.PHP_EOL;
        }
        echo "测试完成".PHP_EOL;
    }

    /**
     * 临时改更新时间order_track
    * @param array params
    */
    public function test_order_track()
    {
        $where = [];
        $where[] = ['latest_sub_status', '=', "Delivered_Other"];
        $lists = Db::name('order_track')
            ->field('id,create_time,update_time')
            ->where($where)
            ->order('id', 'desc')
            ->limit(100000)
            ->select()
            ->toarray();
        $count = count($lists);
        // halt($count);
        
        $executedCount = 0;
        $executedCountsu = 0;
        foreach ($lists as $k=>$v) {
            // halt($v);
            $create_time = strtotime($v['create_time']);
            $update_time = strtotime($v['update_time']);
            $Difference = $update_time - $create_time;
            if ($Difference > 86400 * 30 * 3) {
                $executedCountsu++;
                Db::name('order_track')
                    ->where('id',$v['id'])
                    ->update([
                        'update_time' => $v['create_time'],
                    ]);
            }
            $executedCount++;
            echo "总数：".$count.",当前".$executedCount.",成功".$executedCountsu.PHP_EOL;
        }
        echo "测试完成".PHP_EOL;
    }


    /**
    * 导出客户
    * @param array params
    */
    public function export_test($params = [])
    {
        $header = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'name'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['支付渠道', 'payment_gateway_names'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['币种', 'currency'];
        $header[] = ['原销售额', 'old_total_price'];
        $header[] = ['现销售额', 'total_price'];
        $header[] = ['退款金额参考', 'refund'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['订单付款时间', 'created_at'];
        $header[] = ['退款时间', 'closed_at'];
        $header[] = ['最后更新时间', 'updated_at'];
        $header[] = ['商品SKU', 'sku'];

        $tableName = "export_test";

        $where = [];
        $where[] = ['a.createtime', '>=', 1735660800];
        $where[] = ['a.createtime', '<=', time()];
        $where[]  = ['a.financial_status', 'in', ["refunded", "partially_refunded"]];
        
        // $groups = Db::name('order_achievement')
        //     ->field('
        //     a.fulfillment_status,count(a.id) as num
        //     ')
        //     ->alias('a')
        //     ->where($where)
        //     ->group('a.fulfillment_status')
        //     ->select()
        //     ->toarray();
        // halt($groups);
            

        $lists = Db::name('order_achievement')
            ->field('
            a.shop_id,a.name,a.order_id,a.financial_status,
            a.fulfillment_status,
            a.payment_gateway_names,
            a.refund,
            a.old_total_price,
            a.total_price,
            a.currency,
            a.total_price,
            a.sku,
            b.name as shop_name,
            c.created_at,c.updated_at,c.closed_at
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->join('qu_order c','c.order_id = a.order_id', 'left')
            ->where($where)
            ->order('shop_id desc,c.created_at desc')
            ->select()
            ->toarray();
        
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }
    /**
    * 导出客户
    * @param array params
    */
    public function export_master($params = [])
    {
        $header = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'name'];
        $header[] = ['订单号', 'order_id'];
        $header[] = ['支付渠道', 'payment_gateway_names'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['币种', 'currency'];
        $header[] = ['原销售额', 'old_total_price'];
        $header[] = ['现销售额', 'total_price'];
        $header[] = ['退款金额参考', 'refund'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['订单付款时间', 'created_at'];
        $header[] = ['退款时间', 'closed_at'];
        $header[] = ['最后更新时间', 'updated_at'];
        $header[] = ['商品SKU', 'sku'];
        $header[] = ['标签', 'tags'];

        $tableName = "export_test";

        $where = [];
        $where[] = ['a.createtime', '>=', 1735660800];
        $where[] = ['a.createtime', '<=', time()];
        $where[]  = ['a.tags','like','%Master%'];
        $where[]  = ['a.payment_gateway_names', '=',"shopify_payments"];

        $lists = Db::name('order_achievement')
            ->field('
            a.shop_id,a.name,a.order_id,a.financial_status,
            a.fulfillment_status,
            a.payment_gateway_names,
            a.refund,a.tags,
            a.old_total_price,
            a.total_price,
            a.currency,
            a.total_price,
            a.sku,
            b.name as shop_name,
            c.created_at,c.updated_at,c.closed_at
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->join('qu_order c','c.order_id = a.order_id', 'left')
            ->where($where)
            ->order('shop_id desc,c.created_at desc')
            ->select()
            ->toarray();
            
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }
    /**
    * 导出客户
    * @param array params
    */
    public function export_master2($params = [])
    {
        $header = [];
        $header[] = ['slug', 'slug'];
        $header[] = ['客户', 'author'];
        $header[] = ['信息数量', 'message_count'];
        $header[] = ['创建时间', 'created_at'];
        $header[] = ['标签', 'tag_list'];
        $header[] = ['email', 'email'];
        $header[] = ['店铺', 'brand'];
        $header[] = ['payment_gateway_names', 'payment_gateway_names'];

        $tableName = "export_test";

        $where = [];
        $where[] = ['created_at', '>=', "2025-01-01"];
        $where[]  = ['tag_list','like','%First%'];

        $lists = Db::name('conversations')
            ->field('
                slug,author,message_count,created_at,tag_list,email,brand
            ')
            ->where($where)
            ->select()
            ->toarray();

        $lists_new = [];
        foreach ($lists as $key => $value) {
            $customer = Db::name('order_customer')->where('email',$value['email'])->find();
            $counts = Db::name('order_achievement')
                ->where('order_id',$customer['order_id'])
                ->where('payment_gateway_names',"shopify_payments")
                ->count();
            if($counts > 0){
                $value['payment_gateway_names'] = "shopify_payments";
                $lists_new[] = $value;
            }
        }
            
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists_new, $header, $fileName, 'xlsx');
    }


    /**
     * @desc    获取订单请求地址
     * @date    2024/8/24
     * @author  zhangheng
     */
    public function customer($orderId,$code,$site_url)
    {

        date_default_timezone_set('Asia/Shanghai');
        $url = $site_url."/admin/api/2024-01/graphql.json";
        $query = <<<QUERY
      {
        order(id: "gid://shopify/Order/{$orderId}") {
        customerJourneySummary {
            firstVisit {
            id
            landingPage
            landingPageHtml
            sourceType
            utmParameters {
                campaign
                content
                medium
                source
            }
            },
            lastVisit {
            id
            landingPage
            landingPageHtml
            sourceType
            utmParameters {
                campaign
                content
                medium
                source
            }
            }
        }
        }
    }
QUERY;
            $data = HttpUtil::PostUrlgraphql($url, $code, $query);
            $result = json_decode($data, true);
            $arr = array();
            $arr['order_id'] = $orderId;
            if(!empty($result['data']['order']['customerJourneySummary']) && isset($result['data']['order']['customerJourneySummary'])){
            $customerJourneySummary = $result['data']['order']['customerJourneySummary'];
                if(!empty($customerJourneySummary['firstVisit'])){
                    if(!empty($customerJourneySummary['firstVisit']['utmParameters'])){
                    $arr['firstVisit_campaign'] = $this->removeEmojis($customerJourneySummary['firstVisit']['utmParameters']['campaign']);
                    $arr['firstVisit_source'] = $this->removeEmojis($customerJourneySummary['firstVisit']['utmParameters']['source']);
                    }
                }
                if(!empty($customerJourneySummary['lastVisit'])){
                    if(!empty($customerJourneySummary['lastVisit']['utmParameters'])){
                    $arr['lastVisit_campaign'] = $this->removeEmojis($customerJourneySummary['lastVisit']['utmParameters']['campaign']);
                    $arr['lastVisit_source'] = $this->removeEmojis($customerJourneySummary['lastVisit']['utmParameters']['source']);
                    }
                }
                $arr['graphql_status'] = 1;
            }else{
                $arr['graphql_status'] = 2;
            }
            Db::name('order_source')
                    ->where('order_id',$arr['order_id'])
                    ->update($arr);
            return true;
        }


}
